Linux线程调度
Posted Alvin2012
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux线程调度相关的知识,希望对你有一定的参考价值。
代码如下:
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 "); 18 break; 19 case SCHED_RR: 20 printf("policy = SCHED_RR "); 21 break; 22 case SCHED_OTHER: 23 printf("policy = SCHED_OTHER "); 24 break; 25 default: 26 printf("policy = UNKNOWN "); 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 ", priority); 49 50 priority = sched_get_priority_min(policy); 51 assert(-1 != priority); 52 printf("min_priority = %d ", 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 ", 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 "); 94 api_show_thread_priority(policy); 95 96 printf("Show SCHED_FIFO of priority "); 97 api_show_thread_priority(SCHED_FIFO); 98 99 printf("Show SCHED_RR of priority "); 100 api_show_thread_priority(SCHED_RR); 101 102 printf("Show priority of current thread "); 103 int priority = api_get_thread_priority(&attr); 104 105 printf("Set SCHED_FIFO policy "); 106 api_set_thread_policy(&attr, SCHED_FIFO); 107 108 printf("Set SCHED_RR policy "); 109 api_set_thread_policy(&attr, SCHED_RR); 110 111 printf("Restore current policy "); 112 api_set_thread_policy(&attr, policy); 113 114 printf("Restore current priority "); 115 api_set_thread_priority(&attr, priority); 116 117 rs = pthread_attr_destroy(&attr); 118 assert(0 == rs); 119 120 return 0; 121 }
以上是关于Linux线程调度的主要内容,如果未能解决你的问题,请参考以下文章
Linux 内核线程调度示例一 ④ ( pthread_attr_init 初始化线程属性对象 | 完整代码示例 )
Linux 内核线程调度示例一 ④ ( pthread_attr_init 初始化线程属性对象 | 完整代码示例 )