2013-01-05 63 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"); 
}