Welcome to the 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("\n I am in init\n");

}

</code><br /> <code>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);

}

</code><br /> <code>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);

}

</code><br /> <code>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);

}

</code><br /> <code>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);

}

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training