pthread_setschedprio() fails with "EINVAL"
I just started with pthreads and don't know much about it. I was trying to set the priorities of pthreads using pthread_setschedprio() but it returns "EINVAL". Here is my code:
#include <pthread.h>
#include <errno.h>
void *Run(void *ptr);
class Thread {
public:
pthread_t myPthread;
void start() {
pthread_create( &myPthread, NULL, Run, (void*)this );
}
Thread() { }
virtual void run() = 0;
};
void *Run( void *ptr ) {
Thread* tmp;
tmp = (Thread*)ptr;
tmp->run();
}
class MyThread : public Thread {
public:
virtual void run() {
while (1) {
printf("Running\n");
sleep(1);
}
}
};
MyThread t1;
int main()
{
int status;
t1.start();
status= pthread_setschedprio(t1.myPthread, 300);
if(status!=0)
{
if(status==EPERM)
{
fprintf(stderr,"EPERM\n");
}
else if(status==EINVAL)
{
fprintf(stderr,"EINVAL\n");
}
else
{
fprintf(stderr,"neither EPERM nor EINVAL\n");
}
fprintf(stderr,"error %d\n",status);
errno=status;
perror("");
exit(1);
}
pthread_join( t1.myPthread, NULL);
exit(0);
}
When I try to compile it, I get EINVAL Running error 22 Invalid arg开发者_StackOverflow社区ument
Can anybody tell me why I get the error and how I can solve it?
From this link it looks like it means the priority you specified is invalid for the current scheduling policy. If you look at this page you can determine valid priorities for the different scheduling policies. Finally you can use pthread_getschedparam to determine the current scheduling policy you are using if you are unsure.
Linux normally has its priorities from 0-139. Real-time priorities ranging from 0-99 and dynamic priorities ranging from -19-20 (but actually acting as 100-139).
Negative PR values are the procps tools' way of showing real time threads. In this case the Error is occuring because of the use of the priority 300, which is out of range.
Thread has a scheduling policy and Priority and the parameters passed are to be interpreted along with the Policy.
sched.h actually defines the different types of policies as
#define SCHED_OTHER 0
#define SCHED_FIFO 1
#define SCHED_RR 2
pthread_create is by default creating thread in SCHED_OTHER policy and that is the reason why you observed a zero.
superuser privilages are required if we need to change the priority of a FIFO or RR (Round Robin) Real time threads.
精彩评论