barfatchen barfatchen - 3 months ago 9x
Linux Question

sched_setscheduler is for all threads or main thread?

I have the following source which like to have SCHED_RR priority 90 :

int main(int argc, char** argv)
const char *sched_policy[] = {
struct sched_param sp = {
.sched_priority = 90
pid_t pid = getpid();
sched_setscheduler(pid, SCHED_RR, &sp);
printf("Scheduler Policy is %s.\n", sched_policy[sched_getscheduler(pid)]);

pthread_t tid ;
pthread_create(&tid , NULL, Thread1 , (void*)(long)3);
pthread_create(&tid , NULL, Thread2 , (void*)(long)3);
pthread_create(&tid , NULL, Thread3 , (void*)(long)3);

while shell "top" , I can see that process has PR with -91 , look like it works,
As I know , in Linux , thread1 and thread2 and thread3 are different tasks
from the main thread , they just share the same virtual memory , I like to know
in this test , should I need to add

pthread_setschedparam(pthread_self(), SCHED_RR, &sp);

for all thread1,thread2 and thread3 so that all these 3 can be scheduled
with SCHED_RR ?! or I don't need to do that ?! and how can I observe
that thread1,thread2 and thread3 thread are SCHED_RR or SCHED_OTHER ?!

Edit :

sudo chrt -v -r 90 ./xxx.exe

will see :

pid 7187's new scheduling policy: SCHED_RR
pid 7187's new scheduling priority: 90

how can I be sure this is only for main thread ?! or all threads in pid 7187
are SCHED_RR policy ?! and again , how to observe it ?!


You shall check (and set, if required) the scheduler inheritance attributes before creating any new thread.

int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched);

int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);

The pthread_attr_getinheritsched() will store in the variable pointed by inheritsched one of two possible values:

  • PTHREAD_INHERIT_SCHED - Threads that are created using attr
    inherit scheduling attributes from the creating thread; the scheduling attributes in attr are ignored.

  • PTHREAD_EXPLICIT_SCHED - Threads that are created using attr take their scheduling attributes from the values specified by the attributes object.

If you want that every newly created thread inherits the scheduler attributes of the calling task, you should set PTHREAD_INHERIT_SCHED (if not already set).

Also note:

The default setting of the inherit-scheduler attribute in a newly initialized thread attributes object is PTHREAD_INHERIT_SCHED


$ man pthread_setschedparam
$ man pthread_attr_setinheritsched
  • (Blockquoted material was copied from parts of release 3.74 of the Linux man-pages project.)