设置线程优先级的例子
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <pthread.h> 5 6 void Thread1() 7 { 8 sleep(1); 9 int i,j; 10 int policy; 11 struct sched_param param; 12 pthread_getschedparam(pthread_self(),&policy,¶m); 13 if(policy == SCHED_OTHER) 14 printf("SCHED_OTHER\n"); 15 if(policy == SCHED_RR); 16 printf("SCHED_RR 1 \n"); 17 if(policy==SCHED_FIFO) 18 printf("SCHED_FIFO\n"); 19 20 for(i=1;i<10;i++) 21 { 22 for(j=1;j<5000000;j++) 23 { 24 } 25 printf("thread 1\n"); 26 } 27 printf("Pthread 1 exit\n"); 28 } 29 30 void Thread2() 31 { 32 sleep(1); 33 int i,j,m; 34 int policy; 35 struct sched_param param; 36 pthread_getschedparam(pthread_self(),&policy,¶m); 37 if(policy == SCHED_OTHER) 38 printf("SCHED_OTHER\n"); 39 if(policy == SCHED_RR); 40 printf("SCHED_RR\n"); 41 if(policy==SCHED_FIFO) 42 printf("SCHED_FIFO\n"); 43 44 for(i=1;i<10;i++) 45 { 46 for(j=1;j<5000000;j++) 47 { 48 49 } 50 printf("thread 2\n"); 51 } 52 printf("Pthread 2 exit\n"); 53 } 54 55 void Thread3() 56 { 57 sleep(1); 58 int i,j; 59 int policy; 60 struct sched_param param; 61 pthread_getschedparam(pthread_self(),&policy,¶m); 62 if(policy == SCHED_OTHER) 63 printf("SCHED_OTHER\n"); 64 if(policy == SCHED_RR) 65 printf("SCHED_RR \n"); 66 if(policy==SCHED_FIFO) 67 printf("SCHED_FIFO\n"); 68 69 for(i=1;i<10;i++) 70 { 71 for(j=1;j<5000000;j++) 72 { 73 } 74 printf("thread 3\n"); 75 } 76 printf("Pthread 3 exit\n"); 77 } 78 79 int main() 80 { 81 int i; 82 i = getuid(); 83 if(i==0) 84 printf("The current user is root\n"); 85 else 86 printf("The current user is not root\n"); 87 88 pthread_t ppid1,ppid2,ppid3; 89 struct sched_param param; 90 91 pthread_attr_t attr,attr1,attr2; 92 93 pthread_attr_init(&attr); 94 pthread_attr_init(&attr1); 95 pthread_attr_init(&attr2); 96 param.sched_priority = 51; 97 pthread_attr_setschedpolicy(&attr2,SCHED_RR); 98 pthread_attr_setschedparam(&attr2,¶m); 99 pthread_attr_setinheritsched(&attr2,PTHREAD_EXPLICIT_SCHED);//要使优先级其作用必须要有这句话 100 101 param.sched_priority = 21; 102 pthread_attr_setschedpolicy(&attr1,SCHED_RR); 103 pthread_attr_setschedparam(&attr1,¶m); 104 pthread_attr_setinheritsched(&attr1,PTHREAD_EXPLICIT_SCHED); 105 106 pthread_create(&ppid3,&attr,(void *)Thread3,NULL); 107 pthread_create(&ppid2,&attr1,(void *)Thread2,NULL); 108 pthread_create(&ppid1,&attr2,(void *)Thread1,NULL); //线程1的优先级大于线程2 109 110 pthread_join(ppid3,NULL); 111 pthread_join(ppid2,NULL); 112 pthread_join(ppid1,NULL); 113 pthread_attr_destroy(&attr2); 114 pthread_attr_destroy(&attr1); 115 pthread_attr_destroy(&attr); 116 return 0; 117 }