这是我如何做的基本模板,但经过四周搜索后,我发现旁边没有代码示例,所以我猜测判断是否最佳。
问题是,boost :: thread没有一个构造函数,它允许在创建线程时传递pthead属性,所以你必须在线程启动后进行更改。我知道解决这个问题的唯一方法是通过进程/线程计划继承。除非另有指示,否则新线程将继承其创建者的计划/优先级,以便在创建工作线程之前更改当前线程,然后如果需要则更改回来。看起来很尴尬,但它是一种选择。
下面是一个例子的破解,希望能够解释两者。您可能需要根据需要更改策略和优先级,并以根用户身份运行。
请注意您设置优先级的方式。各种限制适用。
#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 retcode;
int policy;
pthread_t threadID = (pthread_t) daThread.native_handle();
struct sched_param param;
if ((retcode = pthread_getschedparam(threadID, &policy, ¶m)) != 0)
{
errno = retcode;
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 ((retcode = pthread_setschedparam(threadID, policy, ¶m)) != 0)
{
errno = retcode;
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;
}
Arafangion:你有什么要支持的吗? pthread_attr_setschedparam的linux手册页说它可以工作。此外,我个人的经验是,它的工作原理与文件完全一致。 – 2011-11-18 07:10:46