确定调用线程正在运行的CPU?
我是 Pthread 的新手。我写了一个例子来检查我的线程在哪个 CPU 上运行。我已经使用sched_getcpu()来获取调用线程当前正在执行的 CPU 的数量。这是我的代码:
#include <pthread.h>
#include <stdio.h>
void* a(){
printf("1st child thread in CPU %dn",sched_getcpu());
return NULL;
}
void* b(){
printf("2nd child thread in CPU %dn",sched_getcpu());
return NULL;
}
void* c(){
printf("3rd child thread in CPU %dn",sched_getcpu());
return NULL;
}
void* d(){
printf("4th child thread in CPU %dn",sched_getcpu());
return NULL;
}
void* e(){
printf("5th child thread in CPU %dn",sched_getcpu());
return NULL;
}
int main(){
pthread_t t;
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_create(&t,NULL,a,NULL);
pthread_create(&t1,NULL,b,NULL);
pthread_create(&t2,NULL,c,NULL);
pthread_create(&t3,NULL,d,NULL);
pthread_create(&t4,NULL,e,NULL);
pthread_join(t,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_join(t4,NULL);
printf("main thread in CPU %dn",sched_getcpu());
return 0;
}
显然,这个程序的输出每次运行都会发生变化。但这里有一个例子:
输出:
1st child thread in CPU 2
3rd child thread in CPU 2
2nd child thread in CPU 0
4th child thread in CPU 3
5th child thread in CPU 1
main thread in CPU 3
CPU的id号从0变成了3,我的电脑只有2核4线程,为什么输出在0到3之间。输出中 CPU 的 id 是否与物理线程的 id 相等?谢谢!
回答
您的计算机有 2 个内核和 4 个“逻辑处理器”(CPU)。因为您有 4 个 CPU,所以 ID 号从 0 到 3。
这里的主要问题是术语——“CPU”(和“线程”)是如何定义的。您假设“CPU”被定义为“核心”,但大多数人将其定义为“逻辑处理器”或“(硬件)线程”;使用超线程,每个核心有 2 个逻辑处理器,因此最终有 4 个 CPU(来自 2 个核心)。