[英]pthreads with real time priority
我需要管理具有不同優先級的線程池,因此我編寫了以下線程啟動過程:
static
int startup(thrd_t *thrd, thrd_sync_t *sync, int prio)
{
pthread_attr_t attr;
int err;
struct sched_param param = {
.sched_priority = prio
};
assert(pthread_attr_init(&attr) == 0);
assert(pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0);
assert(pthread_attr_setschedparam(&attr, ¶m) == 0);
err = pthread_create(&thrd->handler, &attr, thread_routine, (void *)thrd);
pthread_attr_destroy(&attr);
return err;
}
原則上,不應允許非特權用戶執行此代碼:pthread_create()調用應返回EPERM,因為運行具有高優先級的線程具有安全隱患。
出乎意料的是,它適用於普通用戶,但它根本不尊重給定的優先級。
我嘗試通過刪除pthread_attr_t
並在創建線程后設置調度屬性來修改代碼:
static
int startup(thrd_t *thrd, thrd_sync_t *sync, int prio)
{
pthread_attr_t attr;
int err;
struct sched_param param = {
.sched_priority = prio
};
err = pthread_create(&thrd->handler, NULL /*&attr*/, thread_routine,
(void *)thrd);
if (err != 0) return err;
err = pthread_setschedparam(thrd->handler, SCHED_FIFO, ¶m);
if (err != 0) return err;
return err;
}
順便說一下,這種方法管理起來要困難得多,因為如果出現錯誤,我需要終止新創建的線程。 至少它似乎在權限要求方面正常工作(只有root可以執行此操作),但仍然不遵守優先級。
難道我做錯了什么?
編輯
我剛剛添加了以下一段由每個線程執行的代碼:
static
void getinfo ()
{
struct sched_param param;
int policy;
sched_getparam(0, ¶m);
DEBUG_FMT("Priority of this process: %d", param.sched_priority);
pthread_getschedparam(pthread_self(), &policy, ¶m);
DEBUG_FMT("Priority of the thread: %d, current policy is: %d and should be %d",
param.sched_priority, policy, SCHED_FIFO);
}
使用第一種方法(即pthread_attr_t
方法),結果是pthread_attr_setschedpolicy完全無效,因為優先級為0且策略不是SCHED_FIFO。
使用第二種方法(即pthread_setschedparam
方法),該函數打印預期的數據,但執行仍然以錯誤的方式運行。
我認為您還必須使用pthread_attr_setinheritsched
來確保考慮對優先級設置的更改。 從手冊頁:
PTHREAD_INHERIT_SCHED指定從創建線程繼承調度策略和關聯屬性,並忽略此attr參數中的調度屬性。
PTHREAD_EXPLICIT_SCHED指定將調度策略和關聯的屬性設置為此屬性對象的相應值。
在手冊頁中,您還有以下內容:
新初始化的線程屬性對象中的inherit-scheduler屬性的缺省設置是PTHREAD_INHERIT_SCHED。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.