Welcome to the new Linux Foundation Forum!

Why difference in output when i use pthread_join?

Hi

I have the below code:

When the pthread_join is commented - the order of execution of the threads is different from what happens when pthread_join is retained in the code.

Why is that the case?

#include <pthread.h>

#include <stdio.h>

</code><br /> <code>pthread_once_t once = PTHREAD_ONCE_INIT;

</code><br /> <code>void *myinit()

{

printf(&quot;\n I am in init\n&quot;);

}

</code><br /> <code>void* t1routine(void* i)

{

printf(&quot;\n I am in thread%d\n&quot;, *(int*)i);

pthread_once(&amp;once, (void*)myinit);

printf(&quot;\n I am exiting from thread %d\n&quot;, *(int*)i);

}

</code><br /> <code>void* t2routine(void* i)

{

printf(&quot;\n I am in thread%d\n&quot;, *(int*)i);

pthread_once(&amp;once, (void*)myinit);

printf(&quot;\n I am exiting from thread %d\n&quot;, *(int*)i);

}

</code><br /> <code>void* t3routine(void* i)

{

printf(&quot;\n I am in thread%d\n&quot;, *(int*)i);

pthread_once(&amp;once, (void*)myinit);

printf(&quot;\n I am exiting from thread %d\n&quot;, *(int*)i);

}

</code><br /> <code>main()

{

int id = 1;

pthread_t t1,t2,t3;

pthread_create(&amp;t1, NULL, t1routine, (void*) &amp;id);

pthread_join(t1, NULL);

id++;

pthread_create(&amp;t2, NULL, t2routine, (void*) &amp;id);

pthread_join(t1, NULL);

id++;

pthread_create(&amp;t3, NULL, t3routine, (void*) &amp;id);

pthread_join(t1, NULL);

pthread_exit(NULL);

}

Sign In or Register to comment.