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; //所要設定的線程優先順序 }; |
我們可以通過下面的測試程式來說明,我們自己使用的系統的支援的優先順序:
| #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 |