本文试图从直观角度,说明SCHED_RR调度策略和SCHED_OTHER调度策略之间的区别。
在Linux上,SCHED_OTHER和SCHED_NORMAL的意思相同,它们都是指的CFS调度策略,只不过,在内核中,CFS定义为SCHED_NORMAL,在用户态,CFS定义为SCHED_OTHER.
可参照内核头文件和musl libc头文件:
测试代码如下:
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
void *child_thread(void *arg)
{
int policy = 0;
int max_priority = 0,min_priority = 0;
struct sched_param param;
pthread_attr_t attr;
struct sched_param sp;
bzero((void*)&sp, sizeof(sp));
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED);
pthread_attr_getinheritsched(&attr,&policy);
if(policy == PTHREAD_EXPLICIT_SCHED){
printf("Inheritsched:PTHREAD_EXPLICIT_SCHED\n");
}
if(policy == PTHREAD_INHERIT_SCHED){
printf("Inheritsched:PTHREAD_INHERIT_SCHED\n");
}
//pthread_attr_setschedpolicy(&attr,SCHED_RR);
pthread_attr_setschedpolicy(&attr,SCHED_OTHER);
pthread_attr_getschedpolicy(&attr,&policy);
if(policy == SCHED_FIFO){
printf("Schedpolicy:SCHED_FIFO\n");
}
if(policy == SCHED_RR){
printf("Schedpolicy:SCHED_RR\n");
}
if(policy == SCHED_OTHER){
printf("Schedpolicy:SCHED_OTHER\n");
}
max_priority = sched_get_priority_max(policy);
min_priority = sched_get_priority_min(policy);
printf("Maxpriority:%u\n",max_priority);
printf("Minpriority:%u\n",min_priority);
param.sched_priority = max_priority;
pthread_attr_setschedparam(&attr,¶m);
sp.sched_priority = 1;
// Actually set the sched params for the current thread.
if (0 == pthread_setschedparam(pthread_self(), policy, &sp)) {
printf("IO Thread #%ld using high-priority scheduler!", pthread_self());
}
printf("sched_priority:%u\n",param.sched_priority);
while(1);
pthread_attr_destroy(&attr);
}
int main(int argc,char *argv[ ])
{
pthread_t child_thread_id;
pthread_create(&child_thread_id,NULL,child_thread,NULL);
pthread_join(child_thread_id,NULL);
return 0;
}
代码执行流前首先设置了调度策略为SCHED_OTHER, pthread_attr_setschedpolicy(&attr,SCHED_OTHER);之后执行while(1);循环占住CPU。
执行前通过nice命令设置线程的优先级,由于PC处理器是四核,所以执行四次,让每个CPU上都执行满载,如下图所示:
caozilong@caozilong-