用于线程优先级的 pthread api 非常晦涩难懂,不仅难以理解,而且在 android 上也无法使用。
那么,有没有办法降低或提高线程的优先级?
int currentPolicy;
struct sched_param sched;
status = pthread_getschedparam(pthread_self(), ¤tPolicy, &sched);
printf("sched.sched_priority:%d currentPolicy:%d", sched.sched_priority, currentPolicy);
printf("priority min/max:%d/%d", sched_get_priority_min(currentPolicy), sched_get_priority_max(currentPolicy));
输出:
sched.sched_priority:0 currentPolicy:0
priority min/max:0/0
另外,无论我做什么,pthread_setschedparam 总是为我返回一个错误(无效参数)。 在我的代码中,我需要降低处理程序线程的优先级,以确保其他线程使用更多的 cpu 时间。或者,与我的进程中的其他线程相比,我可以提高我想要用作更多 CPU 的其他线程的线程优先级。
我有什么办法吗?我只使用原生 C++ 代码。
编辑: 从这篇文章看来,android 的线程是某种轻量级进程,可以修改它们的优先级setpriority应该使用。看起来该函数有效(getpriority before 和 after 表示优先级已被修改)。但是,我在我的应用中没有看到预期的效果。
最佳答案
Android 线程是 Linux 线程。他们没什么特别的。
setpriority()
改变线程的“nice”值,这会影响线程被调度的优先级。
pthread_setschedparam()
也可用于更改策略。
一般来说,如果没有提升权限 (CAP_SYS_NICE
),您将无法提高优先级或更改其策略。您可以降低它,或将其恢复为“正常”优先级。
如果你使用 adb shell ps -t -p
你可以看到分配给每个线程的优先级。此信息也包含在 Dalvik 堆栈转储中。
Dalvik 使用 setpriority()
在必要时临时提高 GC 线程的优先级(以避免优先级倒置)。如果你看 this bit of code在第 625 行附近,您可以看到它。您还可以看到对 set_sched_policy()
的调用,这是一个 Android 库函数,它改变了 cgroup线程在里面。
关于android - 在 C/C++ 中更改 Android 上的 native 线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17398075/