我想设置开发的自定义线程池的优先级。所以我发现要设置优先级需要使用 pthred 的
pthread_setschedparam
方法。由于 pthread_t
和 native_handle_type
不同,我做了这样的事情 -
void SetPriority(int id, int priority, int policy) {
bool ret = true;
sched_param sch_params;
sch_params.sched_priority = 20;
pthread_t p;
p.p = threads_[id].native_handle();
if (pthread_setschedparam(p, SCHED_FIFO, &sch_params)) {
std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;
}
}
我遇到了
pthreadVC2.dll
的访问冲突。
为了测试我是否使用正确的 Windows 版本的 dll,我做了一些这样的测试 -
int main(){
pthread_t thread1, thread2;
int thr = 1;
int thr2 = 2;
// start the threads
pthread_create(&thread1, NULL, *threadfn, (void *)thr);
pthread_create(&thread2, NULL, *threadfn, (void *)thr2);
sched_param sch_params;
sch_params.sched_priority = 20;
if (pthread_setschedparam(thread1, SCHED_FIFO, &sch_params)) {
std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;
}
// wait for threads to finish
int po1, po2;
sched_param sched_param1, sched_param2;
pthread_getschedparam(thread1,&po1,&sched_param1);
pthread_getschedparam(thread2, &po2, &sched_param2);
cout << "thread 1:policy - " << po1 << " priority - " << sched_param1.sched_priority << endl;
cout << "thread 2:policy - " << po2 << " priority - " << sched_param2.sched_priority << endl;
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
我发现错误编号为1(未设置优先级)。 并且两个线程都具有策略 0 和优先级 0。
设置 pthread 优先级的正确方法是什么?如何使用
std::thread
中的此功能?
编辑:Windows环境设置: 在 Windows 10 上使用 Visual Studio 2015。 从 ftp://sourceware.org/pub/pthreads-win32/ 下载 pthread (pthreads-w32-2-9-1-release.zip)。 项目设置-包含附加包含目录 Linker > General 并设置 pthread 库的位置 其他依赖项:pthreadVC2.lib 和 pthreadVCE2.lib 并将pthreadVC2.dll复制到项目目录中。
这里是一个示例程序,展示了如何将 pthread_getschedparam 和 pthread_setschedparam 与 std::thread 一起使用,摘自here。
#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>
#include <cstring>
#include <pthread.h>
std::mutex iomutex;
void f(int num)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
sched_param sch;
int policy;
pthread_getschedparam(pthread_self(), &policy, &sch);
std::lock_guard<std::mutex> lk(iomutex);
std::cout << "Thread " << num << " is executing at priority "
<< sch.sched_priority << '\n';
}
int main()
{
std::thread t1(f, 1), t2(f, 2);
sched_param sch;
int policy;
pthread_getschedparam(t1.native_handle(), &policy, &sch);
sch.sched_priority = 20;
if (pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
}
t1.join(); t2.join();
}