在后C ++ 11世界中设置std :: thread实例优先级的正确方法是什么
是否有一种可移植的方式,至少在Windows和POSIX(Linux)环境中有效?
或者是获取句柄并使用特定操作系统可用的本机调用的问题?
没有办法通过C ++ 11库设置线程优先级。我不认为这会在C ++ 14中发生变化,而我的水晶球在此之后对于版本的评论太朦胧了。
在POSIX,pthread_setschedparam(thread.native_handle(), policy, {priority});
我不知道相同的Windows功能,但我确信必须有一个。
我的快速实施......
#include <thread>
#include <pthread.h>
#include <iostream>
#include <cstring>
class thread : public std::thread
{
public:
thread() {}
static void setScheduling(std::thread &th, int policy, int priority) {
sch_params.sched_priority = priority;
if(pthread_setschedparam(th.native_handle(), policy, &sch_params)) {
std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;
}
}
private:
sched_param sch_params;
};
这就是我用它的方式......
// create thread
std::thread example_thread(example_function);
// set scheduling of created thread
thread::setScheduling(example_thread, SCHED_RR, 2);
标准C ++库未定义对线程优先级的任何访问。要设置线程属性,您可以使用std::thread
的native_handle()
并使用它,例如,在带有pthread_getschedparam()
或pthread_setschedparam()
的POSIX系统上。我不知道是否有任何建议将调度属性添加到线程接口。
在Windows中,进程按类和级别优先级进行组织。阅读本文:Scheduling Priorities,它提供了关于线程和进程优先级的良好的整体知识。您可以使用以下函数甚至动态控制优先级:GetPriorityClass(),SetPriorityClass(),SetThreadPriority(),GetThreadPriority()。
显然你也可以在windows系统上使用std::thread
的native_handle()
和pthread_getschedparam()
或pthread_setschedparam()
。检查这个例子,std::thread: Native Handle并注意添加的标题!