c++ 设置线程调度策略以及优先级

377 阅读1分钟

c++ 线程调度及优先级

  • 在 linux 平台上,c++ 线程可以看作是对 pthread 的封装,调用 native_handle 方法可返回底层线程柄,即 pthead_t 描述符,然后,可以使用 pthread 相关api进行相关设置。

示例1

  • 使用 native_handle 方法。可能会出现 Operation not permitted 错误,使用管理员权限执行即可。

    #include <pthread.h>
    #include <cstdio>
    #include <cstring>
    #include <thread>
    #include <chrono>
    
    using namespace std::chrono_literals;
    
    void f(void)
    {
        std::this_thread::sleep_for(1s);
    
        int policy;
        sched_param sch;
        pthread_getschedparam(pthread_self(), &policy, &sch);
        printf("sched policy %d, thread priority %d\n", policy, sch.sched_priority);
    }
    
    int main()
    {
        std::thread t(f);
    
        sched_param sch;
        sch.sched_priority = 20;
        if (pthread_setschedparam(t.native_handle(), SCHED_FIFO, &sch)) {
            printf("set sched param failed - %s\n", strerror(errno));
        }
    
        t.join();
        return 0;
    }