Search code examples
c++pthreadsposixthread-priority

operation not permitted while setting new priority for thread


I have created two threads . By default they have a priority of 0 which I can see using pthread_getschedparam and then I try to increase their priority to say 2 and 3 respectively . But When I try do do so I get an error

     error setting priority for T1: (1), Operation not permitted
     error setting priority for T2: (1), Operation not permitted 

I have used the scheduling policy of SCHED_RR for them

       int sched = SCHED_RR;
       

and then performed this :-

  if (pthread_setschedparam(t1, sched, &t1_param) != 0) 
  {
     std::cout << "error setting priority for T1: (" << errno << "), " << 
     strerror(errno) << std::endl;
  }

What is the reason I am unable to modify my threads priority because priority is within limit of 1 to 99 for SCHED_RR.


Solution

  • DISCLAIMER: I'm not an expert at Linux security, and the following advice might compromise or damage your computer.

    In recent versions of Linux, there is a resource limit, RLIMIT_RTPRIO, which specifies the maximum real-time priority you can use. You can check this from the shell:

    > ulimit -r
    0
    

    On my version of Ubuntu (and probably yours too) there's also a hard limit of zero, so you can't simply use ulimit or setrlimit to raise this. One way to raise the hard limit is to add a line to /etc/security/limits.conf like this (replacing <username> with your username):

    <username> hard rtprio 99
    

    Then you should be able to use ulimit (from the shell) or setrlimit (from your program) to set the soft limit to the priority you need; alternatively, you could set that automatically by adding a second line to limits.conf, replacing hard with soft.

    > ulimit -Hr # show hard limit
    99
    > ulimit -r
    0
    > ulimit -Sr 1 # set soft limit
    > ulimit -r
    1
    

    Do be careful running programs with real-time priority; it can kill the system if it starts misbehaving.