1,线程绑定内核
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>// 定义一个函数,用于设置线程的CPU亲和性
void set_thread_affinity(pthread_t thread, int cpu_id) {
cpu_set_t cpuset;
int s;// 清空CPU集合并添加指定的CPU
CPU_ZERO(&cpuset);
CPU_SET(cpu_id, &cpuset);// 设置线程的CPU亲和性
s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (s != 0) {
perror("pthread_setaffinity_np");
exit(EXIT_FAILURE);
}// 验证设置是否成功
s = pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (s != 0) {
perror("pthread_getaffinity_np");
exit(EXIT_FAILURE);
}// 打印CPU亲和性设置结果
for (int i = 0; i < CPU_SETSIZE; i++) {
if (CPU_ISSET(i, &cpuset)) {
printf("Thread %lu is running on CPU %d\n", thread, i);
}
}
}// 线程函数
void* thread_function(void* arg) {
// 设置本线程的CPU亲和性到CPU 0
set_thread_affinity(pthread_self(), 0);// 执行线程的工作...
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;
}
设置本线程的CPU亲和性到CPU 0使用的函数是 set_thread_affinity(pthread_self(), 0),使用CPU_ZERO
和CPU_SET
宏来初始化一个CPU集合并设置亲和性掩码。
2,进程绑定内核,绑定某个进程到某一个核(核亲和性)
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>int main() {
cpu_set_t cpuset;
pid_t pid;// 获取当前进程的PID
pid = getpid();// 清空CPU集合并设置亲和性掩码
CPU_ZERO(&cpuset);
// 假设我们要绑定到第0个CPU核心上
CPU_SET(0, &cpuset);// 设置当前进程的CPU亲和性
if (sched_setaffinity(pid, sizeof(cpuset), &cpuset) == -1) {
perror("sched_setaffinity");
exit(EXIT_FAILURE);
}// 打印进程ID和设置的CPU亲和性
printf("Process %d bound to CPU %d\n", pid, 0);// 为了演示效果,让进程睡眠一段时间
sleep(60);return EXIT_SUCCESS;
}
查看绑定效果,taskset -p <PID>
taskset -p 688
pid 688's current affinity mask: 1