具有c ++ 11的pthread_setschedparam的std :: thread

时间:2018-06-29 11:36:22

标签: c++ pthreads stdthread

我想设置开发的自定义线程池的优先级。因此我发现设置优先级需要使用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;
}

我发现错误编号为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)。 项目设置-包含其他包含目录 链接器>常规,然后设置pthread库的位置 其他依赖项:pthreadVC2.lib和pthreadVCE2.lib 然后将pthreadVC2.dll复制到项目目录中。

1 个答案:

答案 0 :(得分:1)

这是一个示例程序,显示了如何将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();
}