Increasing thread priority in Linux

It is sometimes useful to get semi-realtime behavior from some of an application’s thread. This is common when I/O latency needs to be kept low, a good example being Software Defined Radio. The software component of the radio would like to read and write samples from the radio as soon as possible, keeping buffers small but also avoiding buffer overflows (on read) and underflows (on write).

A useful technique on Linux/Unix systems is changing threads’ scheduling priority. Linux supports several scheduling policies: SCHED_OTHER, the default scheduling policy, with round-robin sharing; SCHED_BATCH for batch processing; SCHED_IDLE for extremely low priority (background) jobs; and the two real-time priority policies SCHED_FIFO and SCHED_RR for FIFO and round-robin, respectively. In real-time scheduling policies, threads have a priority from 1 to 99, and higher priority threads always preempt lower priority threads. The order among waiting threads with the same priority is determined by the policy (FIFO or round-robin).

Two alternatives exist to set thread scheduling policy and priority: using chrt from the command line, and POSIX threads (also known as pthreads). For chrt, the chrt man page is a useful reference. Below are details and references for the use of pthreads.

The following code sets a thread’s real-time policy to SCHED_FIFO, with the maximum allowable priority. It uses the headers pthread.h and sched.h

We’ll set the priority of the current thread (via pthread_self), although it’s possible to set other threads’ priorities.

Setting thread priority is done through struct sched_param, which contains a sched_priority member. It’s possible to query the maximum and minimum priorities for a policy.

Setting thread priority is one call to pthread_setschedparam.

In some cases it makes sense to verify the thread priority and policy

Hope this snippet is useful. A more complete and involved demonstration (with a main) is available in the pthread_setschedparam man page. This stackoverflow question served as the starting point for this code.

Posted in Tech Blog.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *