多核CPU指定某个线程在某个核心上运行。
在多核处理器上,您可以通过设置CPU 亲和性(CPU Affinity)来强制将一个线程绑定到特定的核心运行。通过设置亲和性,可以限制线程仅运行在指定的一个核心上,避免操作系统的调度器将它迁移到其他核心。
在使用的时候需要 #include <sched.h> 并且需要使用 #define _GNU_SOURCE 来启用GNU的拓展。否则无法使用。
在使用的时候,通过 cpu_set_t cpuset; 并将cpu0或者某个cpu放入到cpuset这个cpu集合中,并通过 pthread_setaffinity_np 来设置某个线程在哪个cpu集合中运行。
如果两个线程在同一个核心上运行,则5s内的计数值的和将是两个线程分别在一个核心上运行的一半。
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
volatile int flag1 = 0; // 线程1的flag
volatile int flag2 = 0; // 线程2的flag
void *thread_func1(void *arg) {
while (1) {
flag1++; // 线程1自增
}
return NULL;
}
void *thread_func2(void *arg) {
while (1) {
flag2++; // 线程2自增
}
return NULL;
}
// 打印线程绑定的CPU核心
void print_thread_affinity(pthread_t thread) {
cpu_set_t cpuset_check;
pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset_check);
if (CPU_ISSET(0, &cpuset_check)) {
printf("Thread is bound to core 0\n");
} else if (CPU_ISSET(1, &cpuset_check)) {
printf("Thread is bound to core 1\n");
} else {
printf("Thread is not bound to core 0 or 1\n");
}
}
int main() {
pthread_t thread1, thread2;
cpu_set_t cpuset1, cpuset2;
// 设置线程1绑定到核心0
CPU_ZERO(&cpuset1);
CPU_SET(0, &cpuset1); // 核心0
pthread_create(&thread1, NULL, thread_func1, NULL);
pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpuset1);
// 设置线程2绑定到核心1
CPU_ZERO(&cpuset2);
CPU_SET(1, &cpuset2); // 核心1
pthread_create(&thread2, NULL, thread_func2, NULL);
pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpuset2);
// 打印每个线程的CPU亲和性
print_thread_affinity(thread1);
print_thread_affinity(thread2);
// 等待线程执行5秒钟
sleep(5);
printf("Flag1: %d, Flag2: %d\n", flag1, flag2);
pthread_cancel(thread1);
pthread_cancel(thread2);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
powered by GPT-4o