How to increase thread priority in pthreads?

Steveng picture Steveng · Sep 6, 2010 · Viewed 95k times · Source

I am using pthread in Linux. I would like to increase the thread priority by setting the parameters sched_param.priority. However, I could not find much info from the net regarding the range of the thread priority I could set, or about the description of the thread priority.

Also, I would like to know about the relative thread priority as I would not want to set the thread priority to be too high and resulting the OS to halt. Could someone help me with this?

Answer

levif picture levif · Sep 8, 2010

The default Linux scheduling policy is SCHED_OTHER, which have no priority choice but a nice level to tweak inside the policy.

You'll have to change to another scheduling policy using function pthread_setschedparam (see also man sched_setscheduler)

'Normal' scheduling policies: (from sched_setscheduler(2))

   SCHED_OTHER   the standard round-robin time-sharing policy;
   SCHED_BATCH   for "batch" style execution of processes; and
   SCHED_IDLE    for running very low priority background jobs.

Real-time scheduling policies:

   SCHED_FIFO    a first-in, first-out policy; and
   SCHED_RR      a round-robin policy.

In your case maybe you can use SCHED_BATCH as this does not require root privileges.

Warning: wrong usage of real-time scheduling policies may hang your system. That's why you need root privileges to do this kind of operation.

Just to be sure of what your machine is capable of, you can use chrt tool from util-linux package.
As an example:

$ chrt -m 
SCHED_OTHER min/max priority    : 0/0
SCHED_FIFO min/max priority     : 1/99
SCHED_RR min/max priority       : 1/99
SCHED_BATCH min/max priority    : 0/0
SCHED_IDLE min/max priority     : 0/0

A way to waste less time (which I often use):

alias batchmake='time chrt --batch 0 make --silent'

While staying with user privileges, this propels the make by 15% (in my case).

Edit: introducing nice, SCHED_BATCH, SCHED_IDLE and chrt tool. For accuracy ! :)