2013-01-05 64 views
6

我有一个单线程应用程序。如果我使用下面的代码,我得到sched_setscheduler(): Operation not permitted 在Linux中更改线程优先级和调度程序

struct sched_param param; 
param.sched_priority = 1; 
if (sched_setscheduler(getpid(), SCHED_RR, &param)) 
printf(stderr, "sched_setscheduler(): %s\n", strerror(errno)); 

但是,如果我使用pthread API如下,我没有得到一个错误。单线程应用程序的两者之间有什么区别,下面的函数是否真的改变了调度程序和优先级,还是我错过了一些错误处理?

void assignRRPriority(int tPriority) 
{ 
    int policy; 
    struct sched_param param; 

    pthread_getschedparam(pthread_self(), &policy, &param); 
    param.sched_priority = tPriority; 
    if(pthread_setschedparam(pthread_self(), SCHED_RR, &param)) 
      printf("error while setting thread priority to %d", tPriority); 
} 

回答

3

的错误可能是由上实时优先级设置(ulimit -r检查,ulimit -r 99允许1-99优先级)的限制​​而引起的。从pthread_setschedparam开始就是成功的:如果你编译时没有使用-pthread选项,这个函数就像一些其他的pthread函数一样是一个存根。使用-pthread选项时,结果应该相同(strace表示使用相同的系统调用)。

+0

1.我确实链接了应用程序和-lpthread。 2. ulimit -r显示0.所以它是如何解释我能够调用值为80的函数assignRRPriority。为什么没有错误? – Jimm

+0

'-lpthread'不够,'-pthread'是必需的(用于_both_编译_and_连接)。然后assignRRPriority将失败。 –

0

你错过了一些基本的错误处理。那里需要一些<。试试这个:

if(pthread_setschedparam(pthread_self(), SCHED_RR, &param) < 0) { 
    perror("pthread_setschedparam"); 
}