Skip to content

Instantly share code, notes, and snippets.

@sandeepkumar-skb
Created November 6, 2020 01:09
Show Gist options
  • Save sandeepkumar-skb/5679b5aa2e1bde7d73276a9aa223def8 to your computer and use it in GitHub Desktop.
Save sandeepkumar-skb/5679b5aa2e1bde7d73276a9aa223def8 to your computer and use it in GitHub Desktop.
Setting priority of a std::thread
#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();
}
@sandeepkumar-skb
Copy link
Author

Compile:
g++ -pthread -Wall -std=c++14 set_thread_priority.cpp -o out.o

Run:
./out.o
If not root then
sudo ./out.o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment