I've tried quite some time to analyse this and I can come up with only one answer - that the process ID printed will be different. but gcc is printing the same value. Can anybody explain why its so?
Please find below example:
#include<stdio.h>
#include<pthread.h>
void *fun_t(void *arg)
{
printf("%d\n",getpid());
pthread_exit("Bye");
}
int main()
{
pthread_t pt;
void *res_t;
if(pthread_create(&pt,NULL,fun_t,NULL) != 0)
perror("pthread_create");
if(pthread_join(pt,&res_t) != 0)
perror("pthread_join");
printf("%d\n",getpid());
return 0;
}
Here's my understanding:
1. New thread with some process ID will be created.
2. It'll begin executing the passed function as soon as the OS schedules it
3. pthread_join will cause the calling thread to wait until the new thread finishes execution.
4. The new thread will print its process ID (which would be different from the main thread).
5. res_t pointer will get populated with the starting address of where "Bye" is stored (but won't be used).
6. in the main thread, getpid() will cause the printf to print the main thread's PID, which would be different from the already printed PID of the new thread.
7. program terminates.
Can someone tell me where i'm wrong? I'm running this in a gcc compiler for windows (win 10 latest version) on a eclipse IDE (also latest version).
Two threads that run in the same process context have the same PID. There were implementations of threading that erroneously gave each thread its own process ID, but those have been obsolete for about a decade now.