Could any explain me the output of the following programs (compiled using gcc (GCC) 4.6.3 version in linux) :
void * thread_routine (void *p)
{
printf("Inside thread : Hello World!\n");
pthread_exit(NULL);
}
int main ()
{
// Object to hold thread ID
pthread_t thread;
int rv,*exit;
// Routine shell create a new thread
rv = pthread_create(&thread, NULL, thread_routine, NULL);
if(rv)
puts("Failed to create thread");
printf("Exit Main\n");
return 0;
}
Output:
Exit Main
Inside thread : Hello World!
Inside thread : Hello World!
I was thinking thread_routine()
will not get a chance to scheduled before which main will return. But output was different. Even if thread_routine is getting scheduled, it should print Inside thread : Hello World!
once. But it is printing it twice.
If I add pthread_self()
in printf
statement inside thread_routine()
, this thread is not getting scheduled, and in this case output is:
Exit Main