创建两个线程,用不同的实时调度(SCHED_FIFO,SCHED_RR)和非实时调度(SCHED_OTHER)策略,总结如下:
#include <sys/time.h> #include <sys/resource.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define __USE_GNU #include <pthread.h> #include <sched.h> long long a = 0; long long b = 0; int attach_cpu(int cpu_index) { int cpu_num = sysconf(_SC_NPROCESSORS_CONF); if (cpu_index < 0 || cpu_index >= cpu_num) { printf("cpu index ERROR!\n"); return -1; } cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu_index, &mask); if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) { printf("set affinity np ERROR!\n"); return -1; } return 0; } void *thread1(void *param) { printf("t1 tid %d\n", gettid()); /*if (setpriority(PRIO_PROCESS, 0, 19) != 0) { printf("setpriority failed!\n"); }*/ attach_cpu(0); long long i; for (i = 0; i < 10000000000; i++) { a++; } } void *thread2(void *param) { printf("t2 tid %d\n", gettid()); if (setpriority(PRIO_PROCESS, 0, -20) != 0) { printf("setpriority failed!\n"); } attach_cpu(0); long long i; for (i = 0; i < 10000000000; i++) { b++; } } //#define C_SET int main() { pthread_t t1; pthread_t t2; #ifdef C_SET pthread_attr_t attr; #else int policy; #endif struct sched_param param; #ifdef C_SET if (pthread_attr_init(&attr) != 0) { printf("pthread_attr_init failed!\n"); return -1; } if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0) { printf("pthread_attr_setinheritsched failed!\n"); } if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0) { printf("pthread_attr_setschedpolicy failed!\n"); } param.sched_priority = 10; if (pthread_attr_setschedparam(&attr, ¶m) != 0) { printf("pthread_attr_setschedparam failed!\n"); } if (pthread_create(&t1, &attr, thread1, NULL) != 0) #else if (pthread_create(&t1, NULL, thread1, NULL) != 0) #endif { printf("create t1 failed!\n"); return -1; } #ifndef C_SET param.sched_priority = 1; policy = SCHED_FIFO; if (pthread_setschedparam(t1, policy, ¶m) != 0) { printf("set t1 sched param failed!\n"); } #endif sleep(1); #ifdef C_SET param.sched_priority = 10; if (pthread_attr_setschedparam(&attr, ¶m) != 0) { printf("pthread_attr_setschedparam failed!\n"); } if (pthread_create(&t2, &attr, thread2, NULL) != 0) #else if (pthread_create(&t2, NULL, thread2, NULL) != 0) #endif { printf("create t2 failed!\n"); return -1; } #ifndef C_SET param.sched_priority = 99; policy = SCHED_FIFO; /* if (pthread_setschedparam(t2, policy, ¶m) != 0) { printf("set t2 sched param failed!\n"); }*/ #endif while (a != 10000000000 || b != 10000000000) { printf("a=%lld, b=%lld\n", a, b); sleep(1); } printf("a=%lld, b=%lld\n", a, b); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }
以上是在x86的ubuntu系统的测试结果,在Android上的测试结果类似,因为都是linux内核。在Android上没有pthread_setaffinity_np(),需要用syscall系统调用。
syscall(__NR_sched_setaffinity, gettid(), sizeof(mask), &mask);
参考:
https://blog.csdn.net/maray/article/details/2900689
联系客服