Linux 线程调度与优先级

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 *attrconst struct sched_param *param);
  int pthread_attr_getschedparam(const pthread_attr_t *attrstruct sched_param *param);
 param.sched_priority = 51//设置优先级

   
系统创建线程时,默认的线程是SCHED_OTHER。所以如果我们要改变线程的调度策略的话,可以通过下面的这个函数实现。

int pthread_attr_setschedpolicy(pthread_attr_t *attrint 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,&param);
  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(

转载于:https://www.cnblogs.com/schips/p/11022910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值