2014-10-07 35 views
0

如何獲得使用初始優先級創建的pthread線程?在下面的代碼中,我聲明瞭執行此操作所必需的上限,事實上,它確實將線程的優先級更改爲15,但由於某些原因,線程始終以優先級0開始,即使我指定它需要SCHED_RR。無法使用SCHED_RR創建pthread優先級

我也通過使用sudo setcap CAP_SYS_NICE+eip [program]確保程序具有正確的功能。我試着以常規用戶和root用戶的身份運行。這兩種情況都是一樣的。

那麼,我錯過了什麼? :)

謝謝!

/* compiled with -lpthread -lcap */ 

#include <stdlib.h> 
#include <stdio.h> 
#include <sys/capability.h> 
#include <pthread.h> 
#include <unistd.h> 

pthread_t mythread; 

void myfunction() 
{ 
    int i ; 
    int err_code; 
    int policy; 
    struct sched_param schedule; 

    for (i=0; i < 70; i++) 
    { 
     pthread_getschedparam(pthread_self(), &policy, &schedule); 
     printf("My policy is %d. My priority is %d\n", policy, schedule.sched_priority); 
     sleep(1); 
    } 
} 

int main() 
{ 
    cap_t caps; 
    char myCaps[] = "cap_sys_nice+eip"; 
    int err_code; 
    int policy = SCHED_RR; 
    struct sched_param schedule; 
    pthread_attr_t attr; 

    caps = cap_from_text(myCaps); 

    if (caps == NULL) 
    { 
     printf("Caps is null :(\n"); 
     return 1; 
    } 

    printf("I have capabilities!\n"); 


    schedule.sched_priority = 80; //SCHED_RR goes from 1 -99 
    pthread_attr_init(&attr); 
    pthread_attr_setschedpolicy(&attr, policy); 
    pthread_attr_setschedparam(&attr, &schedule); 
    pthread_create(&mythread, NULL, (void *) &myFunction, NULL); 
    sleep(3); 

    schedule.sched_priority = 15; //Arbitrary, for testing purposes 

    err_code = pthread_setschedparam(mythread, policy, &schedule); 
    if (err_code != 0) 
    { 
     printf("I have failed you, master! Error: %d\n", err_code); 
    } 

    pthread_join(mythread, NULL); 
    cap_fee(caps); 

    return 0; 
} 

回答

1

事實上,它看起來像你實際上並沒有使用你的電話pthread_create的初始化pthread_attr_t。請注意,您將傳遞NULL作爲參數2.