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>



pthread_once_t once = PTHREAD_ONCE_INIT;



void *myinit()

{

printf("\n I am in init\n");

}



void* t1routine(void* i)

{

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

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

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

}



void* t2routine(void* i)

{

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

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

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

}



void* t3routine(void* i)

{

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

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

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

}



main()

{

int id = 1;

pthread_t t1,t2,t3;

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

pthread_join(t1, NULL);

id++;

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

pthread_join(t1, NULL);

id++;

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

pthread_join(t1, NULL);

pthread_exit(NULL);

}

Sign In or Register to comment.