Linux内核的三种调度策略

一 Linux内核的三种调度策略:  

1,SCHED_OTHER 分时调度策略, 

2,SCHED_FIFO实时调度策略,先到先服务。一旦占用cpu则一直运行。一直运行直到有更高优先级任务到达或自己放弃 

   3,SCHED_RR实时调度策略,时间片轮转。当进程的时间片用完,系统将重新分配时间片,并置于就绪队列尾。放在队列尾保证了所有具有相同优先级的RR任务的调度公平 Linux线程优先级设置

SCHED_OTHER 是不支持优先级使用的,而SCHED_FIFO和SCHED_RR支持优先级的使用,他们分别为1和99,数值越大优先级越高。如果程序控制线程的优先级,一般是用pthread_attr_getschedpolicy来获取系统使用的调度策略,如果是 SCHED_OTHER的话,表明当前策略不支持线程优先级的使用,否则可以。

优先级范围的获得

所设定的优先级范围必须在最大和最小值之间。

  int sched_get_priority_max(int policy);  

  int sched_get_priority_min(int policy);  

  三  设置和获取优先级通过以下两个函数 

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; //所要设定的线程优先级

 }; 

例:创建优先级为10的线程
pthread_attr_t   attr;  
struct   sched_param   param;  
pthread_attr_init(&attr);  
pthread_attr_setschedpolicy(&attr,   SCHED_RR);  
param.sched_priority   =   10;  
pthread_attr_setschedparam(&attr,   &param);  
pthread_create(xxx   ,   &attr   ,   xxx   ,   xxx);  
例:设置最高优先级

pthread_attr_t attr;

struct sched_param  param;

pthread_t  thread = pthread_self();//当前程序线程号

int rs = pthread_attr_init( &attr );

                   assert( rs == 0 );

pthread_attr_setschedpolicy(&attr,SCHED_FIFO);//设置线程调度策略

param.sched_priority   =  sched_get_priority_max(SCHED_FIFO); //优先级设定

rs = pthread_attr_setschedparam( &attr,  &param );//设置和获取schedparam属性pthread_attr_destroy(&attr);   

编译

编译命令:

#g++ pthread_priority3.c -o pthread_priority3 -lpthread

否则,会有如下错误
/tmp/cc21HcoW.o(.text+0x4c): In function `main':
: undefined reference to `pthread_create'
collect2: ld returned 1 exit status
可以看出是在ld的时候系统无法找到pthread_create函数。也就是说编译器在link得时候找不到其中的一个使用库的函数。
如果差pthread_create的话可以发现其在pthread.so中,所以需要增加 -lpthread编译参数,告诉linker在link的时候使用pthread模块

原文地址:https://www.cnblogs.com/zhouhbing/p/3904827.html