linux – Set thread priority in C++11

Question:

In the program I'm developing I have two std::threads that are always active throughout the life of the program. However, I consider the role of one of them to be of minor importance and would like to change their priority.

I looked through the documentation and didn't find any function that sets the priority of std::thread.

My question is: how do I set the priority of a std::thread? Is it possible or does the operating system itself take care of setting this at runtime?

Note: The program will only run on Linux (Debian), so there is no need for porting with Windows.

Answer:

There is no way to change the priority of a std::thread in C++11 or C++14. The only way to do this would be by using linux functions (not portable). Get a native handle with std::thread::native_handle() and use it with the pthread_setschedparam function. An example (taken from the first reference):

#include <thread>
#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 << " executando na prioridade "
              << 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 << "setschedparam falhou: " << std::strerror(errno) << '\n';
    }

    t1.join(); t2.join();
}

On Windows the same idea can be applied with SetThreadPriority .

Scroll to Top