首页 > 代码库 > thread_16

thread_16

#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <sched.h>#include <sched.h>void *consumer1(void *p){        do{          printf("<<<(%u),%d\n", (unsigned)pthread_self(),1);        }while(1);} void *consumer2(void *p) {         do{             printf("<<<(%u),%d\n", (unsigned)pthread_self(), 2);             struct sched_param sched;             sched.__sched_priority = 99;        //pthread_setschedparam(*(pthread_t *)p, SCHED_FIFO, &sched);        }while(1); }int main(int argc, char *argv[]){        pthread_t  t1, t2, t3;         int ret;        struct sched_param param;         param.sched_priority = 1;        pthread_attr_t attr;        pthread_attr_init(&attr);                  pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);         pthread_attr_setschedpolicy(&attr, SCHED_FIFO);         pthread_attr_setschedparam(&attr, &param);                 ret = pthread_create(&t1, NULL, consumer1, NULL);        sleep(2);         ret = pthread_create(&t2, &attr, consumer2,(void *)&t1);//注意看最后一个参数         if(ret != 0)         {                printf("create failed,%d\n", ret);               exit(1);         }         pthread_attr_destroy(&attr);         sleep(1);         printf("main returned\n");      return 0; } /*运行结果:1.最终一直运行  void *consumer1(void *p),2.如果把18行注释掉,最终一直运行void *consumer2(void *p),3.在18行第一个子线程的被改为实时并优先级大于第二个线程,所以它抢占cpu并一直运行。4.如果第一个线程优先级设置小于第二个线程,还是一直运行void *consumer2(void *p)。  5.如果17, 18行改为sched.__sched_priority = 0;pthread_setschedparam(pthread_self(), SCHED_OTHER,     &sched);第二个线程将会变为普通线程*/

 

thread_16