• 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 *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 ");
        break;
      case SCHED_RR:
        printf("policy= SCHED_RR");
        break;
      case SCHED_OTHER:
        printf("policy=SCHED_OTHER ");
        break;
      default:
        printf("policy=UNKNOWN ");
        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 ",priority);
      priority= sched_get_priority_min(policy);
      assert(priority!=-1);
      printf("min_priority=%d ",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 ");
        show_thread_priority(&attr,policy);
      printf("show SCHED_FIFO of priority ");
     show_thread_priority(&attr,SCHED_FIFO);
      printf("show SCHED_RR of priority ");
      show_thread_priority(&attr,SCHED_RR);
      printf("show priority of current thread ");
      int priority = get_thread_priority(&attr);

      printf("Set thread policy ");
      printf("set SCHED_FIFO policy ");
      set_thread_policy(&attr,SCHED_FIFO);
      printf("set SCHED_RR policy ");
      set_thread_policy(&attr,SCHED_RR);
      printf("Restore current policy ");
      set_thread_policy(&attr,policy);

      rs = pthread_attr_destroy(&attr);
      assert(rs==0);
      return 0;
    }

    下面是测试程序的运行结果:

    policy=SCHED_OTHER
    Show current configuration of priority
    max_priority=0
    min_priority=0
    show SCHED_FIFO of priority
    max_priority=99
    min_priority=1
    show SCHED_RR of priority
    max_priority=99
    min_priority=1
    show priority of current thread
    priority=0Set thread policy
    set SCHED_FIFO policy
    policy= SCHED_FIFO
    set SCHED_RR policy
    policy= SCHED_RRRestore current policy
    policy=SCHED_OTHER

     

     

    这里测试一下其中的两种特性,SCHED_OTHER和SCHED_RR,还有就是优先级的问题,是不是能够保证,高优先级的线程,就可以保证先运行。
        下面的这个测试程序,创建了三个线程,默认创建的线程的调度策略是SCHED_OTHER,其余的两个线程的调度策略设置成SCHED_RR。我的Linux的内核版本是2.6.31。SCHED_RR是根据时间片来确定线程的调度。时间片用完了,不管这个线程的优先级有多高都不会在运行,而是进入就绪队列中,等待下一个时间片的到了,那这个时间片到底要持续多长时间?在《深入理解Linux内核》中的第七章进程调度中,是这样描诉的,Linux采取单凭经验的方法,即选择尽可能长、同时能保持良好相应时间的一个时间片。这里也没有给出一个具体的时间来,可能会根据不同的CPU 来定,还有就是多CPU 的情况。

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <pthread.h>

    void Thread1()
    {
      sleep(1);
      int i,j;
      int policy;
      struct sched_param param;
      pthread_getschedparam(pthread_self(),&policy,&param);
      if(policy == SCHED_OTHER)
        printf("SCHED_OTHER ");
      if(policy == SCHED_RR);
      printf("SCHED_RR 1 ");
      if(policy==SCHED_FIFO)
        printf("SCHED_FIFO ");

      for(i=1;i<10;i++)
      {
        for(j=1;j<5000000;j++)
        {
        }
        printf("thread 1 ");
      }
      printf("Pthread 1 exit ");
    }

    void Thread2()
    {
      sleep(1);
      int i,j,m;
      int policy;
      struct sched_param param;
    pthread_getschedparam(pthread_self(),&policy,&param);
     if(policy == SCHED_OTHER)
        printf("SCHED_OTHER ");
      if(policy == SCHED_RR);
      printf("SCHED_RR ");
      if(policy==SCHED_FIFO)
        printf("SCHED_FIFO ");

      for(i=1;i<10;i++)
      {
        for(j=1;j<5000000;j++)
        {
          
        }
        printf("thread 2 ");
      }
      printf("Pthread 2 exit ");
    }

    void Thread3()
    {
      sleep(1);
      int i,j;
      int policy;
      struct sched_param param;
    pthread_getschedparam(pthread_self(),&policy,&param);
     if(policy == SCHED_OTHER)
        printf("SCHED_OTHER ");
      if(policy == SCHED_RR)
        printf("SCHED_RR ");
      if(policy==SCHED_FIFO)
        printf("SCHED_FIFO ");

      for(i=1;i<10;i++)
      {
        for(j=1;j<5000000;j++)
        {
        }
        printf("thread 3 ");
      }
      printf("Pthread 3 exit ");
    }

    int main()
    {
      int i;
      i = getuid();
      if(i==0)
        printf("The current user is root ");
      else
        printf("The current user is not root ");

      pthread_t ppid1,ppid2,ppid3;
      struct sched_param param;

      pthread_attr_t attr,attr1,attr2;
      
      pthread_attr_init(&attr1);
    pthread_attr_init(&attr);
    pthread_attr_init(&attr2);
     
     param.sched_priority = 51;
     pthread_attr_setschedpolicy(&attr2,SCHED_RR);
     pthread_attr_setschedparam(&attr2,&param);
     pthread_attr_setinheritsched(&attr2,PTHREAD_EXPLICIT_SCHED);//要使优先级其作用必须要有这句话

     param.sched_priority = 21;
     pthread_attr_setschedpolicy(&attr1,SCHED_RR);
     pthread_attr_setschedparam(&attr1,&param);
     pthread_attr_setinheritsched(&attr1,PTHREAD_EXPLICIT_SCHED);
     
     pthread_create(&ppid3,&attr,(void *)Thread3,NULL);
     pthread_create(&ppid2,&attr1,(void *)Thread2,NULL);
     pthread_create(&ppid1,&attr2,(void *)Thread1,NULL);
     
     pthread_join(ppid3,NULL);
     pthread_join(ppid2,NULL);
     pthread_join(ppid1,NULL);
     pthread_attr_destroy(&attr2);
     pthread_attr_destroy(&attr1);
     return 0;
    }

    下面是该程序的其中之一的运行结果:                 注意运行时必须加sudo权限,才能进行优先级抢占

    sudo ./prio_test
    The current user is root
    SCHED_OTHER
    SCHED_RR
    SCHED_RR 1 
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    Pthread 1 exit
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    Pthread 2 exit
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    Pthread 3 exit

       这里我们可以看到,由于线程3的调度策略是SCHED_OTHER,而线程2的调度策略是SCHED_RR,所以,在Thread3中,线程3被线程1,线程2给抢占了。由于线程1的优先级大于线程2的优先级,所以,在线程1以先于线程2运行,不过,这里线程2有一部分代码还是先于线程1运行了。
        我原以为,只要线程的优先级高,就会一定先运行,其实,这样的理解是片面的,特别是在SMP的PC机上更会增加其不确定性。
        其实,普通进程的调度,是CPU根据进程优先级算出时间片,这样并不能一定保证高优先级的进程一定先运行,只不过和优先级低的进程相比,通常优先级较高的进程获得的CPU时间片会更长而已。其实,如果要想保证一个线程运行完在运行另一个线程的话,就要使用多线程的同步技术,信号量,条件变量等方法。
    而不是绝对依靠优先级的高低,来保证。
        不过,从运行的结果上,我们可以看到,
    调度策略为SCHED_RR的线程1,线程2确实抢占了调度策略为SCHED_OTHER的线程3。这个是可以理解的,由于SCHER_RR是实时调度策略。
       只有在下述事件之一发生时,实时进程才会被另外一个进程取代。
      (1) 进程被另外一个具有更高实时优先级的实时进程抢占。
      (2) 进程执行了阻塞操作并进入睡眠
      (3)进程停止(处于TASK_STOPPED 或TASK_TRACED状态)或被杀死。
      (4)进程通过调用系统调用sched_yield(),自愿放弃CPU 。
      (5)进程基于时间片轮转的实时进程(SCHED_RR),而且用完了它的时间片。
       基于时间片轮转的实时进程是,不是真正的改变进程的优先级,而是改变进程的基本时间片的长度。所以基于时间片轮转的进程调度,并不能保证高优先级的进程先运行。
       下面是另一种运行结果:

    sudo ./prio_test
    The current user is root
    SCHED_OTHER
    SCHED_RR 1 
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    thread 1
    Pthread 1 exit
    SCHED_RR
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    thread 2
    Pthread 2 exit
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    thread 3
    Pthread 3 exit

      可以看出并没有每一次都保证高优先级的线程先运行。


    转自:

    https://www.cnblogs.com/xiaotlili/p/3510224.html



    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------


    Linux编程-线程优先级的设定

    最近在学习Linux的编程,这里在博客中记录一下学习的过程。

          对于线程的优先级设定,在网上也看了不少的文章,大多数都只介绍了一个线程,关键是介绍的例程,设置的线程优先级都不起作用。由于之前接触的Linux编程知识比较少,这个问题困扰了我一晚上。于是接着在网上看资料,终于能够使线程的优先级设置有效。

    1、相关知识介绍

          首先总结一下,线程优先级设置的条件:

          a、线程的调度策略必须为:SCHED_RR或SCHED_FIFO;

          b、线程的继承策略必须为:PTHREAD_EXPLICIT_SCHED

          对于继承策略,这里举个简单的例子:

          如果线程A创建了线程B,则线程B的调度策略与线程A的调度策略和线程B的继承策略有关的:

    如果线程B继承策略为PTHREAD_INHERIT_SCHED,则线程B的调度策略与线程A相同,线程B的优先级也与线程A相同,但是线程B不能够自己修改调度策略与优先级(个人理解,不对请指教);

         如果线程B继承策略PTHREAD_EXPLICIT_SCHED,则线程B的调度策略由线程属性attr决定,可以自行设置调度策略与优先级。

          其中继承策略必须为PTHREAD_EXPLICIT_SCHED,否则设置线程的优先级会被忽略

    2、程序示例:

          在设置继承的调度策略 时,只有具有root权限的用户才能执行pthread_attr_setinheritsched操作,否则创建线程会失败。

          下面是一个简单的设置优先级的程序示例,通过修改任务1与任务2的优先级高低,可以观察到打印信息中,先打印的是优先级高的任务的信息:

    /*
    ********************************************************************************
    *描述:设置线程优先级
    *Use:gcc prio.c -lpthread
    *By:Ailson Jack
    *Date:2016.03.25
    *Blog:www.only2fire.com
    ********************************************************************************
    */
    
    #include        <stdio.h>
    #include        <stdlib.h>
    #include        <unistd.h>
    #include        <pthread.h>
    #include        <string.h>
    #include        <time.h>
    
    //在用户层或者应用层,1表示优先级最低,99表示优先级最高
    #define Task1_Prio      6
    #define Task2_Prio      7
    
    pthread_barrier_t barrier;
    
    void *Task1(void *arg);
    void *Task2(void *arg);
    
    int main(void)
    {
        int policy,inher;
        pthread_t tid;
        pthread_attr_t attr;
        struct sched_param param;
        
        pthread_barrier_init(&barrier,NULL,2+1);
    
        //初始化线程属性
        pthread_attr_init(&attr);
        //获取继承的调度策略
        pthread_attr_getinheritsched(&attr,&inher);
    
        if(inher == PTHREAD_EXPLICIT_SCHED)
            printf("PTHREAD_EXPLICIT_SCHED
    ");
        else if(inher == PTHREAD_INHERIT_SCHED)
        {
            printf("PTHREAD_INHERIT_SCHED
    ");
            //必需设置inher的属性为 PTHREAD_EXPLICIT_SCHED,否则设置线程的优先级会被忽略
            inher = PTHREAD_EXPLICIT_SCHED;
        }
    
        //设置继承的调度策略
        //具有root权限的用户才能执行pthread_attr_setinheritsched操作,
        //否则创建线程会失败
        pthread_attr_setinheritsched(&attr,inher);
        //设置线程调度策略
        policy = SCHED_FIFO;
        pthread_attr_setschedpolicy(&attr,policy);
        //设置调度参数
        param.sched_priority = Task1_Prio;
        pthread_attr_setschedparam(&attr,¶m);
        //创建线程
        pthread_create(&tid, &attr,Task1,NULL);
    
        //设置调度参数
        param.sched_priority = Task2_Prio;
        pthread_attr_setschedparam(&attr,¶m);
        //创建线程
        pthread_create(&tid, &attr,Task2,NULL);
        
        sleep(1);
        pthread_barrier_wait(&barrier);
        pthread_join(tid, NULL);
    }
    
    void *Task1(void *arg)
    {
        pthread_barrier_wait(&barrier);
        while(1)
        {
            printf("Task1 is running.
    ");
            sleep(3);//延时3s
        }
        pthread_exit(NULL);
    }
    
    void *Task2(void *arg)
    {
        pthread_barrier_wait(&barrier);
        while(1)
        {
            printf("Task2 is running.
    ");
            sleep(3);//延时3s
        }
        pthread_exit(NULL);
    }
    编译运行程序,由于任务2的优先级比任务1的优先级高,因此打印信息,先打印的是任务2

    转自:http://blog.csdn.net/jackailson/article/details/51058094




    --------------------------------------------------------------------------------------------------------------------------------------


    //我修改的。设置继承的调度策略 时,只有具有root权限的用户才能执行pthread_attr_setinheritsched操作,否则创建线程会失败。

    /*运行时必须加sudo权限,才能进行优先级抢占
    ********************************************************************************
    *描述:设置线程优先级
    *Use:gcc prio.c -lpthread
    *By:Ailson Jack
    *Date:2016.03.25
    *Blog:www.only2fire.com
    ********************************************************************************
    */
    
    #include        <stdio.h>
    #include        <stdlib.h>
    #include        <unistd.h>
    #include        <pthread.h>
    #include        <string.h>
    #include        <time.h>
    
    //在用户层或者应用层,1表示优先级最低,99表示优先级最高
    #define Task1_Prio      6
    #define Task2_Prio      7
    
    
    void *Task1(void *arg);
    void *Task2(void *arg);
    
    int main(void)
    {
        int policy,inher;
        pthread_t tid1,tid2;
        pthread_attr_t attr;
        struct sched_param param;
        int i;
        
    	  i = getuid();
    	  if(i==0)
    	    printf("The current user is root
    ");
    	  else
    	    printf("The current user is not root
    ");
    	  
    
        //初始化线程属性
        pthread_attr_init(&attr);
        //获取继承的调度策略
        pthread_attr_getinheritsched(&attr,&inher);
    
        if(inher == PTHREAD_EXPLICIT_SCHED)
            printf("PTHREAD_EXPLICIT_SCHED
    ");
        else if(inher == PTHREAD_INHERIT_SCHED)
        {
            printf("PTHREAD_INHERIT_SCHED
    ");
            //必需设置inher的属性为 PTHREAD_EXPLICIT_SCHED,否则设置线程的优先级会被忽略
            inher = PTHREAD_EXPLICIT_SCHED;
        }
    
        //设置继承的调度策略
        //具有root权限的用户才能执行pthread_attr_setinheritsched操作,
        //否则创建线程会失败
        pthread_attr_setinheritsched(&attr,inher);
        //设置线程调度策略
        policy = SCHED_FIFO;
        pthread_attr_setschedpolicy(&attr,policy);
        //设置调度参数
        param.sched_priority = Task1_Prio;
        pthread_attr_setschedparam(&attr,¶m);
        //创建线程
        pthread_create(&tid1, &attr,Task1,NULL);
    
    
    
        //设置调度参数
        param.sched_priority = Task2_Prio;
        pthread_attr_setschedparam(&attr,¶m);
        //创建线程
        pthread_create(&tid2, &attr,Task2,NULL);
        
        sleep(1);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
        pthread_attr_destroy(&attr);
    }
    
    void *Task1(void *arg)
    {
        while(1)
        {
            printf("Task1 is running.
    ");
            sleep(3);//延时3s
        }
        pthread_exit(NULL);
    }
    
    void *Task2(void *arg)
    {
        while(1)
        {
            printf("Task2 is running.
    ");
            sleep(3);//延时3s
        }
        pthread_exit(NULL);
    }


    编译、运行:
    gcc -o priority2 priority2.c -lpthread

    sudo ./priority2


    The current user is root
    PTHREAD_INHERIT_SCHED
    Task1 is running.
    Task2 is running.
    Task2 is running.
    Task1 is running.
    Task2 is running.
    Task1 is running.
    Task2 is running.
    Task1 is running.


    在查看运行结果,可以发现  “并不是优先级高的先运行!”

        我原以为,只要线程的优先级高,就会一定先运行,其实,这样的理解是片面的,特别是在SMP的PC机上更会增加其不确定性。
        其实,普通进程的调度,是CPU根据进程优先级算出时间片,这样并不能一定保证高优先级的进程一定先运行,只不过和优先级低的进程相比,通常优先级较高的进程获得的CPU时间片会更长而已。其实,如果要想保证一个线程运行完在运行另一个线程的话,就要使用多线程的同步技术,信号量,条件变量等方法。
    而不是绝对依靠优先级的高低,来保证。

  • 相关阅读:
    hdu 3652 【数位dp】
    02 -body标签中相关标签
    01-html介绍和head标签
    python 核心编程第九章文件
    python核心编程 第七章 字典,集合 练习
    常用链接
    python核心编程 第七章 字典
    python核心编程 第六章 字符串,元组,列表 字符串元组只读不可变。列表可变。
    python核心编程 第五章 数字
    python读取文件中的路径内容,保存到另外的路径中
  • 原文地址:https://www.cnblogs.com/alan666/p/8311907.html
Copyright © 2020-2023  润新知