在Linux中使用Boost设置线程优先级

Boost库似乎没有用于设置线程优先级的设备。这是在Linux上使用的最佳代码,还是有更好的方法?

boost::thread myThread( MyFunction() );

struct sched_param param;

param.sched_priority = 90;

pthread_attr_setschedparam( myThread.native_handle(), SCHED_RR, &param);

我没有很多Linux编程经验。

回答:

那是我如何做的基本模板,但是在搜索之后,我发现几乎没有代码示例,因此我猜想是关于最佳还是无效的判断。

问题在于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 retcode;

int policy;

pthread_t threadID = (pthread_t) daThread.native_handle();

struct sched_param param;

if ((retcode = pthread_getschedparam(threadID, &policy, &param)) != 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, &param)) != 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(), &param)) == -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, &param)) == -1)

{

perror("sched_setscheduler");

exit(EXIT_FAILURE);

}

boost::thread t1(&threadfunc);

displayAndChange(t1);

t1.join();

return 0;

}

以上是 在Linux中使用Boost设置线程优先级 的全部内容, 来源链接: utcz.com/qa/424807.html

回到顶部