Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way of setting std::thread priority in C++11

What is the correct way in the post C++11 world for setting the priority of an instance of std::thread

Is there a portable way of doing this that works at least in Windows and POSIX (Linux) environments?

Or is it a matter of getting a handle and using whatever native calls are available for the particular OS?

like image 391
Gerdiner Avatar asked Sep 19 '13 00:09

Gerdiner


People also ask

Is std :: thread portable?

Your best bet by far is to use the new std::threads library, this is portable and standardised and written in a modern style.

Which method is used for setting priority to threads?

The setPriority() method of thread class is used to change the thread's priority. Every thread has a priority which is represented by the integer number between 1 to 10. Thread class provides 3 constant properties: public static int MIN_PRIORITY: It is the maximum priority of a thread.

Can we set different priority of a thread in C#?

A programmer can explicitly assign priority to a thread. The by default priority of a thread is Normal. Operating system does not assign the priority of threads. If a thread has reached a final state, such as Aborted, then this will give ThreadStateException .

How do I set thread priority in Linux?

The equivalent to SetThreadPriority in linux would be pthread_setschedprio(pthread_t thread, int priority) . Check the man page. This sample is for the default scheduling policy which is SCHED_OTHER. EDIT: thread attribute must be initialized before usage.


2 Answers

There's no way to set thread priorities via the C++11 library. I don't think this is going to change in C++14, and my crystal ball is too hazy to comment on versions after that.

In POSIX, pthread_setschedparam(thread.native_handle(), policy, {priority});

In Win32 BOOL SetThreadPriority(HANDLE hThread,int nPriority)

like image 178
Mike Seymour Avatar answered Sep 20 '22 00:09

Mike Seymour


My quick implementation...

#include <thread> #include <pthread.h> #include <iostream> #include <cstring>  class thread : public std::thread {   public:     thread() {}     static void setScheduling(std::thread &th, int policy, int priority) {         sch_params.sched_priority = priority;         if(pthread_setschedparam(th.native_handle(), policy, &sch_params)) {             std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;         }     }   private:     sched_param sch_params; }; 

and this is how I use it...

// create thread std::thread example_thread(example_function);  // set scheduling of created thread thread::setScheduling(example_thread, SCHED_RR, 2); 
like image 35
marc Avatar answered Sep 20 '22 00:09

marc