Created
November 6, 2020 01:09
-
-
Save sandeepkumar-skb/5679b5aa2e1bde7d73276a9aa223def8 to your computer and use it in GitHub Desktop.
Setting priority of a std::thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <pthread.h> | |
#include <iostream> | |
#include <cstring> | |
class thread : public std::thread | |
{ | |
public: | |
static void setScheduling(std::thread &th, int priority) { | |
sched_param sch; | |
sch.sched_priority = priority; | |
if(pthread_setschedparam(th.native_handle(), SCHED_FIFO, &sch)) { | |
std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl; | |
} | |
} | |
}; | |
void f(int num) { | |
sched_param sch; | |
int policy; | |
pthread_getschedparam(pthread_self(), &policy, &sch); | |
std::cout << "Thread " << num << " priority " << sch.sched_priority << '\n'; | |
} | |
int main(){ | |
std::thread t1, t2; | |
t1 = std::thread(f, 1); | |
t2 = std::thread(f, 2); | |
thread::setScheduling(t1, 99); | |
t1.join(); t2.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile:
g++ -pthread -Wall -std=c++14 set_thread_priority.cpp -o out.o
Run:
./out.o
If not root then
sudo ./out.o