In a recent project I had the need to raise the priority of the currently executing thread for a short period of time while an important I/O operation was being performed (the device which the data was read from didn’t have a buffer to store the data hence the reading thread had to be ready at all times to receive the data). I ended up creating a helper class which uses RAII to manage the priority of the current thread. When the object is created on the local scope the priority of the thread is raised and when the object goes out of scope then the destructor will make sure that the priority of the current thread will go back to its original value.
The class deletes the overload of the operator ‘new’ which makes sure that it is impossible to create the object on the free store.
The code to get the current thread and to change the thread priority is Windows specific but I guess this can quite easily be modified to fit other OS:s as well.
/** The class ThreadPriority is used to temporarily raise the priority of a thread.
The object should be allocated on the stack, NEVER on the free store !
it will automatically change the running threads priority when it is created
it will automatically restore the running threads priority when it goes out of scope. */
HANDLE curThread = GetCurrentThread();
m_oldPriority = GetThreadPriority(curThread);
/** Deleting the new' operator to make sure no one
creates a ThreadPriority object on the free store */
template<typename... Args> void* operator new(std::size_t,Args...) = delete;