LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Difference in output when using pthread_join?? (https://www.linuxquestions.org/questions/linux-newbie-8/difference-in-output-when-using-pthread_join-4175543198/)

VaniJ 05-21-2015 03:20 AM

Difference in output when using pthread_join??
 
For the below code, I observe that when pthread_join is commented from the code - the order of thread execution is not consistent (the main thread executes first and then the remaining threads - in what sequence I am not sure). But when pthread_join is present in the code - I see that order of execution of the threads is as per the code (First t1, then t2 and finally main exits....I can tell that for sure by observing the increasing value of id in main())

Can anybody tell me why that happens?


#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(t2, NULL);
id++;

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

pan64 05-21-2015 03:23 AM

that is explained on the man page of pthread_join:
Quote:

The pthread_join() function waits for the thread specified by thread to terminate.

VaniJ 05-21-2015 03:37 AM

Basics!!..
Thanks for reminding...
Now I am clear :-)


All times are GMT -5. The time now is 05:09 PM.