Linux priority 基本概念可參考
此篇介紹,摘錄如下:
In Linux system priorities are 0 to 139 in which 0 to 99 for real time and 100 to 139 for users. nice value range is -20 to +19 where -20 is highest, 0 default and +19 is lowest.
The relation between nice value and priority is :
PR = 20 + NI
so , the value of PR = 20 + (-20 to +19) is 0 to 39 that maps 100 to 139.
Linux schedule policy 分成兩大類,如下:
- normal (只能修改 nice value 進行調整, 調整後的 priortiy 介於 100~139)
- real-time (調整後的 priortiy 介於 0~99)
其優先權如下
SCHED_FIFO = SCHED_RR > SCHED_OTHER ~ SCHED_BATCH > SCHED_IDLE
我們可藉著設定 process schedule policy ,更改 process priority,舉例如下
1. 建立 thread 時,指定 priority
struct sched_param param;
param.sched_priority = 1;
s = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (s != 0)
handle_error_en(s, "pthread_attr_setinheritsched");
s = pthread_attr_setschedpolicy(&attr, SCHED_RR);
if (s != 0)
handle_error_en(s, "pthread_attr_setschedpolicy");
param.sched_priority = sched_get_priority_min(SCHED_RR);
s = pthread_attr_setschedparam(&attr, ¶m);
if (s != 0)
handle_error_en(s, "pthread_attr_setschedparam");
2. 當 thread 建立之後,動態改變 priority
struct sched_param param;
param.sched_priority = 1;
pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
另外當程式執行之後,可以使用下列命令,得知各個 Thread 的 priority
$ ps H -C a.out -o 'pid tid pri nice cmd comm'
PID TID PRI NI CMD COMMAND
16062 16062 19 0 ./a.out 123 a.out
16062 16063 41 - ./a.out 123 ./a_client
注意:此處 PRI 跟使用 top 看到的 priority 會有差距,其換算公式為 priority = 39 - PRI
Reference: