Linux內核的三種調度策略:
1,SCHED_OTHER 分時調度策略,
2,SCHED_FIFO實時調度策略,先到先服務。一旦占用cpu則一直運行。一直運行直到有更高優先級任務到達或自己放棄
3,SCHED_RR實時調度策略,時間片輪轉。當進程的時間片用完,系統將重新分配時間片,並置於就緒隊列尾。放在隊列尾保證了所有具有相同優先級的RR任務的調度公平
Linux線程優先級設置
首先,可以通過以下兩個函數來獲得線程可以設置的最高和最低優先級,函數中的策略即上述三種策略的宏定義:
int sched_get_priority_max(int policy);
int sched_get_priority_min(int policy);
SCHED_OTHER是不支持優先級使用的,而SCHED_FIFO和SCHED_RR支持優先級的使用,他們分別為1和99,數值越大優先級越高。
設置和獲取優先級通過以下兩個函數
| int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param); int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param); param.sched_priority = 51; //設置優先級 |
系統創建線程時,默認的線程是SCHED_OTHER。所以如果我們要改變線程的調度策略的話,可以通過下面的這個函數實現。
| int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy); |
上面的param使用了下面的這個數據結構:
| struct sched_param { int __sched_priority; //所要設定的線程優先級 /* Scheduling priority */ }; 但是我在linux里使用: man pthread_attr_setschedpolicy ,發現結構體是下面的這種類型 struct sched_param { int sched_priority; /* Scheduling priority */ }; |
我們可以通過下面的測試程序來說明,我們自己使用的系統的支持的優先級:
| #include <stdio.h> #include <pthread.h> #include <sched.h> #include <assert.h> static int get_thread_policy(pthread_attr_t *attr) { int policy; int rs = pthread_attr_getschedpolicy(attr,&policy); assert(rs==0); switch(policy) { case SCHED_FIFO: printf("policy= SCHED_FIFO\n"); break; case SCHED_RR: printf("policy= SCHED_RR"); break; case SCHED_OTHER: printf("policy=SCHED_OTHER\n"); break; default: printf("policy=UNKNOWN\n"); break; } return policy; } static void show_thread_priority(pthread_attr_t *attr,int policy) { int priority = sched_get_priority_max(policy); assert(priority!=-1); printf("max_priority=%d\n",priority); priority= sched_get_priority_min(policy); assert(priority!=-1); printf("min_priority=%d\n",priority); } static int get_thread_priority(pthread_attr_t *attr) { struct sched_param param; int rs = pthread_attr_getschedparam(attr,¶m); assert(rs==0); printf("priority=%d",param.__sched_priority); return param.__sched_priority; } static void set_thread_policy(pthread_attr_t *attr,int policy) { int rs = pthread_attr_setschedpolicy(attr,policy); assert(rs==0); get_thread_policy(attr); } int main(void) { pthread_attr_t attr; struct sched_param sched; int rs; rs = pthread_attr_init(&attr); assert(rs==0); int policy = get_thread_policy(&attr); printf("Show current configuration of priority\n"); show_thread_priority(&attr,policy); printf("show SCHED_FIFO of priority\n"); show_thread_priority(&attr,SCHED_FIFO); printf("show SCHED_RR of priority\n"); |