Linux进程、线程绑定CPU以及独占CPU

mac2025-09-24  25

在很早之前就了解一项技术:线程绑定cpu。该项技术也应用到各种应用软件,来提高性能。这里把自己做的一个实验记录下来,方便日后查阅。

一、进程绑定cpu

我们通过系统调用sched_setaffinity进行绑定,通过sched_getaffinity获取绑定关系。注意这对方法是进程级别的绑定。代码中指定cpu0和cpu3,我们可以通过htop查看,两个cpu使用达到了100%,其他的cpu均不会(正常场景)。

#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; }

二、线程绑定

对于线程绑定,我们需要借助pthread库,通过函数pthread_setaffinity_np来设置绑定cpu关系。我们通过htop查看,会放发现cpu0和cpu3使用率达到100%。 

#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上,但仍然不能独自享有,时间片到了也是有可能被切换出去。那么有什么方法将可以独占某个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要非常谨慎,搞不好系统会起不来啊

最新回复(0)