那是我如何做的基本模板,但是在搜索之后,我发现几乎没有代码示例,因此我猜想是关于最佳还是无效的判断。
问题在于boost ::
thread没有允许在创建线程时传递pthead属性的构造函数,因此您必须在线程启动后进行更改。我知道解决该问题的唯一其他方法是通过进程/线程调度继承。除非另有指示,否则新线程将继承其创建者的计划/优先级,因此您可以在创建工作线程之前更改当前线程,然后根据需要更改。似乎很尴尬,但这是另一种选择。
这是一个希望能同时说明两者的示例。您可能需要适当地更改策略和优先级并以root用户身份运行。
设置优先级时要小心。有各种限制。
#include <iostream>#include <boost/thread/thread.hpp>#include <unistd.h>#include <sched.h>#include <cstdio>void* threadfunc(){ sleep(5);}void displayAndChange(boost::thread& daThread){ int retpre; int policy; pthread_t threadID = (pthread_t) daThread.native_handle(); struct sched_param param; if ((retpre = pthread_getschedparam(threadID, &policy, ¶m)) != 0) { errno = retpre; perror("pthread_getschedparam"); exit(EXIT_FAILURE); } std::cout << "INHERITED: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl; policy = SCHED_FIFO; param.sched_priority = 4; if ((retpre = pthread_setschedparam(threadID, policy, ¶m)) != 0) { errno = retpre; perror("pthread_setschedparam"); exit(EXIT_FAILURE); } std::cout << " CHANGED: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl;}int main(int argc, char* argv[]){ int policy, res; struct sched_param param; if ((policy = sched_getscheduler(getpid())) == -1) { perror("sched_getscheduler"); exit(EXIT_FAILURE); } if ((res = sched_getparam(getpid(), ¶m)) == -1) { perror("sched_getparam"); exit(EXIT_FAILURE); } std::cout << " ORIGINAL: "; std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER" : "???") << ", priority=" << param.sched_priority << std::endl; policy = SCHED_RR; param.sched_priority = 2; if ((res = sched_setscheduler(getpid(), policy, ¶m)) == -1) { perror("sched_setscheduler"); exit(EXIT_FAILURE); } boost::thread t1(&threadfunc); displayAndChange(t1); t1.join(); return 0;}


