编写一段代码 将3个线程绑到3个cpu核上,并输出每个线程的核号
时间: 2023-08-28 13:55:45 浏览: 50
以下是一个将3个线程绑定到3个CPU核心并输出每个线程所绑定核心编号的代码示例:
```c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
void* threadFunc(void* arg) {
int* cpuId = (int*) arg;
int threadId = pthread_self();
cpu_set_t cpuSet;
CPU_ZERO(&cpuSet); // 清空CPU集合
CPU_SET(*cpuId, &cpuSet); // 设置要绑定的CPU核心
if (sched_setaffinity(threadId, sizeof(cpuSet), &cpuSet) == -1) {
perror("绑定CPU核心失败");
exit(EXIT_FAILURE);
}
printf("线程 %lu 绑定到 CPU 核心 %d\n", threadId, *cpuId);
// 在此处编写线程要执行的代码
return NULL;
}
int main() {
pthread_t threads[3];
int cpuIds[3] = {0, 1, 2}; // 要绑定的CPU核心编号
for (int i = 0; i < 3; i++) {
if (pthread_create(&threads[i], NULL, threadFunc, &cpuIds[i]) != 0) {
perror("创建线程失败");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
在上述代码中,我们创建了3个线程,并将每个线程绑定到对应的CPU核心。线程函数 `threadFunc` 接收一个整型指针参数 `arg`,该参数指向要绑定的CPU核心编号。我们使用 `sched_setaffinity` 函数将每个线程绑定到指定的CPU核心上,并输出每个线程所绑定的核心编号。
在 `main` 函数中,我们循环创建3个线程,并将每个线程的 `threadFunc` 函数作为线程函数。然后,我们使用 `pthread_join` 函数等待每个线程执行完毕。
请注意,此代码示例同样适用于Linux系统。在其他操作系统上,可能需要使用不同的API来实现线程绑定功能。