在Linux系统中,线程绑定CPU(也称为CPU亲和性设置)是指将线程限制在特定的CPU核心上运行。这种技术可以通过pthread_setaffinity_np
函数来实现,它是POSIX线程库(pthread)中的一个非标准扩展函数。
CPU亲和性:CPU亲和性是指进程或线程与CPU核心之间的关联关系。通过设置CPU亲和性,可以控制进程或线程在哪些CPU核心上运行。
以下是一个使用pthread_setaffinity_np
函数将线程绑定到特定CPU核心的示例代码:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
void* thread_func(void* arg) {
printf("Thread running on CPU: %d\n", sched_getcpu());
return NULL;
}
int main() {
pthread_t thread;
cpu_set_t cpuset;
int cpu = 1; // 绑定到CPU核心1
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
if (pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset) != 0) {
perror("pthread_setaffinity_np");
exit(EXIT_FAILURE);
}
pthread_join(thread, NULL);
return 0;
}
sudo
提升权限或者修改系统配置来解决。lscpu
命令查看系统中的CPU核心信息,确保指定的核心存在。通过合理使用CPU亲和性设置,可以优化系统性能,提高应用的执行效率。