I'm new to Pthread. I have written an example to check which CPU my thread is running on. I have used sched_getcpu() to get the number of the CPU on which the calling thread is currently executing. Here is my code:
#include <pthread.h>
#include <stdio.h>
void* a(){
printf("1st child thread in CPU %d\n",sched_getcpu());
return NULL;
}
void* b(){
printf("2nd child thread in CPU %d\n",sched_getcpu());
return NULL;
}
void* c(){
printf("3rd child thread in CPU %d\n",sched_getcpu());
return NULL;
}
void* d(){
printf("4th child thread in CPU %d\n",sched_getcpu());
return NULL;
}
void* e(){
printf("5th child thread in CPU %d\n",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 %d\n",sched_getcpu());
return 0;
}
Obviously, the output of this program will change every running time. But here is an example:
Output:
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
The id number of the CPU changed from 0 to 3. I wonder why the output was in the range of 0 to 3 while my computer only has 2 cores and 4 threads. Did the id of the CPU in output equaled with the id of the physical thread? Thanks!
Your computer has 2 cores and 4 "logical processors" (CPUs). Because you have 4 CPUs the ID numbers are from 0 to 3.
The main problem here is terminology - how "CPU" (and "thread") is defined. You're assuming "CPU" is defined as "core", but most people define it as "logical processor" or "(hardware) thread"; and with hyper-threading you have 2 logical processors per core so you end up with 4 CPUs (from 2 cores).
My two cents for pthread beginners:
add:
#include <sched.h>
as per: https://man7.org/linux/man-pages/man3/sched_getcpu.3.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.