线程或进程独占CPU一般用来相对地提升实时性,但也不要指忘达到真正的实时操作系统的性能.
进程邦定CPU
我们通过系统调用sched_setaffinity
进行绑定,通过sched_getaffinity
获取绑定关系。注意这对方法是进程级别的绑定。代码中指定cpu0和cpu3,我们可以通过htop查看,两个cpu使用达到了100%,其他的cpu均不会(正常场景)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#define _GNU_SOURCE /* See feature_test_macros(7) */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sched.h> #include <pthread.h> void* testfunc(void* t) { while(1); return NULL; } int main() { cpu_set_t mask; printf("pid=%d\n", getpid()); CPU_ZERO(&mask); CPU_SET(0, &mask);//将cpu0绑定 CPU_SET(3, &mask);//将cpu3绑定 sched_setaffinity(0, sizeof(cpu_set_t), &mask) ; pthread_t tid1;//创建线程1 if (pthread_create(&tid1, NULL, (void *)testfunc, NULL) != 0) { fprintf(stderr, "thread create failed\n"); return -1; } pthread_t tid2;//创建线程2 if (pthread_create(&tid2, NULL, (void *)testfunc, NULL) != 0) { fprintf(stderr, "thread create failed\n"); return -1; } pthread_join(tid1, NULL); pthread_join(tid1, NULL); return 0; } |
线程邦定CPU
对于线程绑定,我们需要借助pthread库,通过函数pthread_setaffinity_np
来设置绑定cpu关系。我们通过htop查看,会放发现cpu0和cpu3使用率达到100%。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#define _GNU_SOURCE /* See feature_test_macros(7) */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sched.h> #include <pthread.h> void* testfunc(void* t) { int i = 3; while(i) { sleep(5); printf("tid=%d,cpu=%d\n",pthread_self(), sched_getcpu()); i--; } while(1); return NULL; } int main() { cpu_set_t mask; printf("pid=%d\n", getpid()); CPU_ZERO(&mask); pthread_t tid1; if (pthread_create(&tid1, NULL, (void *)testfunc, NULL) != 0) { fprintf(stderr, "thread create failed\n"); return -1; } pthread_t tid2; if (pthread_create(&tid2, NULL, (void *)testfunc, NULL) != 0) { fprintf(stderr, "thread create failed\n"); return -1; } printf("tid1=%d,tid2=%d\n", tid1,tid2); CPU_SET(0, &mask);//绑定cpu0 pthread_setaffinity_np(tid1, sizeof(cpu_set_t), &mask) ; //清除之前设置,重新设置绑定cpu3 CPU_ZERO(&mask); CPU_SET(3, &mask); pthread_setaffinity_np(tid2, sizeof(cpu_set_t), &mask) ; pthread_join(tid1, NULL); pthread_join(tid1, NULL); return 0; } |
配置内核禁止调度到某些核心
上面的设置只能保证进程或者线程运行在特定的cpu上,但仍然不能独自享有,时间片到了也是有可能被切换出去。那么有什么方法将可以独占某个cpu呢?答案是肯定。我们可以设置linux 启动参数grub,在启动参数后面增加isolcpus=a,b,c
。具体修改如下:
编辑grub文件后再执行该命令grub2-mkconfig -o /boot/grub2/grub.cfg
更新grub,重要,重要,重要。
这样在系统启动后,操作系统就不会把任务调度到cpu0和cpu3上。但是我通过htop观察cpu0、cpu3使用率,并非始终是0,而是有略微的变化,后来经过查询相关说明,内核线程任然会调度到cpu0和cpu3上。也就是说这种方式只能控制用户进程。
接下我们就可以通过sched_setaffinity
方式进行绑定,以达到独占效果,但是操作grub要非常谨慎,搞不好系统会起不来啊