设置CPU亲和性基本步骤:
- 获取线程ID:使用
pthread_self()
函数获取当前线程的ID。
- 创建CPU亲和性掩码:使用
cpu_set_t
类型创建一个CPU亲和性掩码,并使用CPU_ZERO()
宏初始化该掩码,然后使用CPU_SET()
宏将需要绑定的CPU核心编号添加到掩码中。
- 设置CPU亲和性:使用
pthread_setaffinity_np()
函数将线程与设置好的CPU亲和性掩码进行绑定。
示例代码:
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
void* thread_function(void* arg) {
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(0, &cpu_set);
if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) != 0) {
perror("pthread_setaffinity_np");
}
printf("Thread is running on CPU: %d\n", sched_getcpu());
return NULL;
}
int main() {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
perror("pthread_create");
return 1;
}
if (pthread_join(thread, NULL) != 0) {
perror("pthread_join");
return 1;
}
return 0;
}