Thread creation using pthread_create with SCHED_RR scheduling fails

1.7k Views Asked by At

I try to write some cores for create a pthread with SCHED_RR:

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, SCHED_RR);
struct sched_param params;
params.sched_priority = 10;
pthread_attr_setschedparam(&attr, &params);
pthread_create(&m_thread, &attr, &startThread, NULL);
pthread_attr_destroy(&attr);

But the thread does't run, do I need set more parameters?

1

There are 1 best solutions below

0
On

A thread can only set the scheduling to SCHED_OTHER without the CAP_SYS_NICE capability. From sched(7):

   In Linux kernels before 2.6.12, only privileged (CAP_SYS_NICE)
   threads can set a nonzero static priority (i.e., set a real-time
   scheduling policy).  The only change that an unprivileged thread can
   make is to set the SCHED_OTHER policy, and this can be done only if
   the effective user ID of the caller matches the real or effective
   user ID of the target thread (i.e., the thread specified by pid)
   whose policy is being changed.

That means when you set the scheduling policy to round-robin scheduling (SCHED_RR) using pthread_attr_setschedpolicy() it's failed in all likelihood (unless you have enabled this capability for the user you are running as or running the program as sysadmin/root user who can override CAP_SYS_NICE).

You can set the capability using the setcap program:

$ sudo setcap cap_sys_nice=+ep ./a.out

(assuming a.out is your program name).

You'd have figured this out if you did error checking. You should check the return value of all the pthread functions (and generally all the library functions) for failure.

Since you haven't posted the full code, it might be an issue if you haven't joined with the thread you create (as main thread could exit before the m_thread was created and this exit the whole process). So, you might want to join:

pthread_join(m_thread, NULL);

or you could exit main thread without joining if main thread is no longer needed using pthread_exit(NULL); in main().