1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <pthread.h> 5 #define THREAD_COUNT 12 6 7 void show_thread_policy(int threadno){ 8 int policy; 9 struct sched_param param; 10 pthread_getschedparam(pthread_self(), &policy, ¶m); 11 switch(policy){ 12 case SCHED_OTHER: 13 printf("SCHED_OTHER %d ", threadno); 14 break; 15 case SCHED_RR: 16 printf("SCHED_RR %d ", threadno); 17 break; 18 case SCHED_FIFO: 19 printf("SCHED_FIFO %d ", threadno); 20 break; 21 default: 22 printf("UNKNOWN "); 23 } 24 } 25 26 void *thread(void *arg){ 27 int i,j; 28 long threadno = (long)arg; 29 printf("thread %d start ", threadno); 30 printf("thread ------------------------------0 "); 31 sleep(1); 32 printf("---------1--------------- "); 33 show_thread_policy(threadno); 34 printf("---------2--------------- "); 35 for(int i=0;i<10;i++){ 36 printf("---------3--------------- "); 37 for(j=0;j<10000000;j++){ 38 39 } 40 41 printf("thread %d ", threadno); 42 } 43 44 printf("thread %d exit ", threadno); 45 return NULL; 46 } 47 48 int main(int argc, char *argv[]){ 49 long i; 50 pthread_attr_t attr[THREAD_COUNT]; 51 pthread_t pth[THREAD_COUNT]; 52 struct sched_param param; 53 for(i=0;i<THREAD_COUNT;++i){ 54 pthread_attr_init(&attr[i]); 55 for(i=0;i<THREAD_COUNT/2;++i){ 56 param.sched_priority = 10; 57 pthread_attr_setschedpolicy(&attr[i], SCHED_FIFO); 58 pthread_attr_setschedparam(&attr[i], ¶m); 59 pthread_attr_setinheritsched(&attr[i], PTHREAD_EXPLICIT_SCHED); 60 } 61 62 for(i=THREAD_COUNT/2;i<THREAD_COUNT;++i){ 63 param.sched_priority = 20; 64 pthread_attr_setschedpolicy(&attr[i], SCHED_FIFO); 65 pthread_attr_setschedparam(&attr[i], ¶m); 66 pthread_attr_setinheritsched(&attr[i], PTHREAD_EXPLICIT_SCHED); 67 } 68 69 for(i=0;i<THREAD_COUNT;++i){ 70 pthread_create(&pth[i], &attr[i], thread, (void *)i); 71 printf("--------------------create thread %d------------ ", i); 72 } 73 74 for(i=0;i<THREAD_COUNT;++i){ 75 pthread_join(pth[i], NULL); 76 } 77 78 for(i=0;i<THREAD_COUNT;++i){ 79 pthread_attr_destroy(&attr[i]); 80 } 81 82 return 0; 83 } 84 }
编译之后执行的结果如下:
[root@Alston C++]# ./thread_2.exe
thread 0 start
thread ------------------------------0
--------------------create thread 0------------
--------------------create thread 1------------
--------------------create thread 2------------
--------------------create thread 3------------
Segmentation fault (core dumped)
目前还没调查出来原因。