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!