std::线程与 pthread_setschedparam 与 C++ 11.

std::thread with pthread_setschedparam with c++ 11

本文关键字:C++ setschedparam pthread 线程 std      更新时间:2023-10-16

我想设置开发的自定义线程池的优先级。 所以我发现设置优先级需要使用 pthred 的pthread_setschedparam方法。由于pthread_tnative_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;
}

我发现错误 no 是 1(未设置优先级(。 并且两个线程都具有策略 0 和优先级 0

设置pthread优先级的正确方法是什么,我如何使用std::thread的此功能?

编辑:视窗环境设置: 将 Visual Studio 2015 与 Windows 10 配合使用。 从 ftp://sourceware.org/pub/pthreads-win32/下载了 pthread (pthreads-w32-2-9-1-release.zip(。 项目设置 - 包括 其他包含目录 链接器>常规并设置线程库的位置 其他依赖项:pthreadVC2.lib 和 pthreadVCE2.lib 并将 pthreadVC2.dll 复制到项目目录中。

这是一个示例程序,展示了如何将 pthread_getschedparam 和 pthread_setschedparam 与 std::thread 一起使用,取自此处。

#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();
}
相关文章:
  • 没有找到相关文章