2016-12-28 131 views
1

我試着寫一些核心的創建SCHED_RR一個並行線程:線程創建失敗

pthread_attr_t attr; 
pthread_attr_init(&attr); 
pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED); 
pthread_attr_setschedpolicy(&attr, SCHED_RR); 
struct sched_param params; 
params.sched_priority = 10; 
pthread_attr_setschedparam(&attr, &params); 
pthread_create(&m_thread, &attr, &startThread, NULL); 
pthread_attr_destroy(&attr); 

但線程開不跑,我還需要更多的設置參數?

回答

0

線程只能將調度設置爲SCHED_OTHER而不具有CAP_SYS_NICE的功能。從sched(7)

In Linux kernels before 2.6.12, only privileged (CAP_SYS_NICE) 
    threads can set a nonzero static priority (i.e., set a real-time 
    scheduling policy). The only change that an unprivileged thread can 
    make is to set the SCHED_OTHER policy, and this can be done only if 
    the effective user ID of the caller matches the real or effective 
    user ID of the target thread (i.e., the thread specified by pid) 
    whose policy is being changed. 

這意味着,當你設置的調度策略使用pthread_attr_setschedpolicy()它未能在所有的可能性(除非您已啓用此功能爲您正在運行的或運行用戶輪詢調度(SCHED_RR)程序作爲系統管理員/ root用戶,可以覆蓋CAP_SYS_NICE)。

您可以使用setcap程序設置功能:

$ sudo setcap cap_sys_nice=+ep ./a.out 

(假設a.out是你的程序名)。

如果您進行了錯誤檢查,那麼您已經想通了。您應該檢查所有pthread函數(通常是所有庫函數)的返回值是否失敗。

既然你還沒有發佈完整的代碼,它可能如果你沒有與您共創線程加入是一個問題(如主要線程m_thread創建之前可能退出,這出全處理)。所以,你可能想參加:

pthread_join(m_thread, NULL); 

,或者你可以退出主線程,如果沒有主線程使用主pthread_exit(NULL);()不再需要加入。