代码如下:
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <sched.h> 4 #include <assert.h> 5 6 static int api_get_thread_policy(pthread_attr_t *attr) 7 { 8 int policy = 0; 9 int rs = 0; 10 11 rs = pthread_attr_getschedpolicy(attr, &policy); 12 assert(0 == rs); 13 14 switch(policy) 15 { 16 case SCHED_FIFO: 17 printf("policy = SCHED_FIFO\n"); 18 break; 19 case SCHED_RR: 20 printf("policy = SCHED_RR\n"); 21 break; 22 case SCHED_OTHER: 23 printf("policy = SCHED_OTHER\n"); 24 break; 25 default: 26 printf("policy = UNKNOWN\n"); 27 break; 28 } 29 30 return policy; 31 } 32 33 static void api_set_thread_policy(pthread_attr_t *attr, int policy) 34 { 35 int rs = 0; 36 37 rs = pthread_attr_setschedpolicy(attr, policy); 38 assert(0 == rs); 39 (void)api_get_thread_policy(attr); 40 } 41 42 static void api_show_thread_priority(int policy) 43 { 44 int priority = 0; 45 46 priority = sched_get_priority_max(policy); 47 assert(-1 != priority); 48 printf("max_priority = %d\n", priority); 49 50 priority = sched_get_priority_min(policy); 51 assert(-1 != priority); 52 printf("min_priority = %d\n", priority); 53 } 54 55 static int api_get_thread_priority(pthread_attr_t *attr) 56 { 57 struct sched_param param; 58 int rs = 0; 59 60 rs = pthread_attr_getschedparam(attr, ¶m); 61 assert(0 == rs); 62 printf("priority = %d\n", param.__sched_priority); 63 64 return param.sched_priority; 65 } 66 67 static void api_set_thread_priority(pthread_attr_t *attr, int priority) 68 { 69 struct sched_param param; 70 int rs = 0; 71 72 rs = pthread_attr_getschedparam(attr, ¶m); 73 assert(0 == rs); 74 75 param.__sched_priority = priority; 76 rs = pthread_attr_setschedparam(attr, ¶m); 77 assert(0 == rs); 78 79 (void)api_get_thread_priority(attr); 80 } 81 82 //int api_set_policy_priority_main() 83 int main() 84 { 85 pthread_attr_t attr; 86 int rs = 0; 87 88 rs = pthread_attr_init(&attr); 89 assert(0 == rs); 90 91 int policy = api_get_thread_policy(&attr); 92 93 printf("Show current configuration of priofity\n"); 94 api_show_thread_priority(policy); 95 96 printf("Show SCHED_FIFO of priority\n"); 97 api_show_thread_priority(SCHED_FIFO); 98 99 printf("Show SCHED_RR of priority\n"); 100 api_show_thread_priority(SCHED_RR); 101 102 printf("Show priority of current thread\n"); 103 int priority = api_get_thread_priority(&attr); 104 105 printf("Set SCHED_FIFO policy\n"); 106 api_set_thread_policy(&attr, SCHED_FIFO); 107 108 printf("Set SCHED_RR policy\n"); 109 api_set_thread_policy(&attr, SCHED_RR); 110 111 printf("Restore current policy\n"); 112 api_set_thread_policy(&attr, policy); 113 114 printf("Restore current priority\n"); 115 api_set_thread_priority(&attr, priority); 116 117 rs = pthread_attr_destroy(&attr); 118 assert(0 == rs); 119 120 return 0; 121 }
原文地址:https://www.cnblogs.com/live-program/p/12625384.html
时间: 2024-10-31 04:31:40