考虑到下面的一些代码,我想知道在linux下假设pthreads甚至是使用Boost.Thread API的代码是多less。
#include <windows.h> int main() { SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST); return 0; }
在Linux中相当于SetThreadPriority
将是pthread_setschedprio(pthread_t thread, int priority)
。
检查手册页 。
编辑:这里是等效的示例代码:
#include <pthread.h> int main() { pthread_t thId = pthread_self(); pthread_attr_t thAttr; int policy = 0; int max_prio_for_policy = 0; pthread_attr_init(&thAttr); pthread_attr_getschedpolicy(&thAttr, &policy); max_prio_for_policy = sched_get_priority_max(policy); pthread_setschedprio(thId, max_prio_for_policy); pthread_attr_destroy(&thAttr); return 0; }
此示例是针对SCHED_OTHER的默认调度策略。
编辑:线程属性必须在使用前初始化。
你要:
#include <pthread.h> int main() { int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, ¶m); param.sched_priority = sched_get_priority_max(policy); pthread_setschedparam(pthread_self(), policy, ¶m); return 0; }
POSIX标准包括pthread_setschedparam(3)
,正如其他各种答案所述。 在讨论实时线程时,大部分都提到了POSIX线程库函数,但是POSIX标准并没有将它的使用仅限于实时线程的领域。 但是,在Linux中,如果使用实时调度类SCHED_FIFO
或SCHED_RR
,则它的使用只有真正有意义,因为只有那些调度类允许多个值作为priority参数。 看到这个堆栈溢出答案的插图。
幸运的是,不幸的是,这是一个问题,似乎主流Linux POSIX线程库实现(过时的LinuxThreads和当前的NPTL实现)并不完全符合POSIX,因为“nice值”不是特定于进程的,而是线程特定的参数,所以看起来你可以使用setpriority(3)
来改变Linux中线程的setpriority(3)
。 此声明基于pthreads(7)
手册页(在该页面中搜索“nice value” pthreads(7)
的兼容性说明; 我在实践中没有经过实际测试(直接做的事)。
如果你决定使用POSIX不兼容的方式来改变线程的优良性,请注意,有人决定修正提到的不符合的潜在可能性,在这种情况下,似乎没有办法改变Linux中的线程优先级使用正常的调度类( SCHED_OTHER
)。
像pthread_setschedparam()
和策略和优先级的组合。
我想你会使用策略SCHED_FIFO, SCHED_RR
你可以指定线程的优先级。
对于那些可能正在寻找基于BSD的操作系统解决方案(如MacOS或iOS)的用户,如果需要,可以考虑使用mach来代替POSIX对等设置线程的优先级。
#include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/sched.h> #include <pthread.h> int set_realtime(int period, int computation, int constraint) { struct thread_time_constraint_policy ttcpolicy; int ret; thread_port_t threadport = pthread_mach_thread_np(pthread_self()); ttcpolicy.period=period; // HZ/160 ttcpolicy.computation=computation; // HZ/3300; ttcpolicy.constraint=constraint; // HZ/2200; ttcpolicy.preemptible=1; if ((ret=thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) { fprintf(stderr, "set_realtime() failed.\n"); return 0; } return 1; }
来源: https : //developer.apple.com/library/content/documentation/Darwin/Conceptual/coreelProgramming/scheduler/scheduler.html