Program:
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
void* pfun1(void *vargp);
void* pfun2(void *vargp);
void main(){
int treturn,jreturn;
pthread_t tid1,tid2;
printf("Before thread call\n");
treturn = pthread_create(&tid1,NULL,pfun1,NULL);
treturn = pthread_create(&tid2,NULL,pfun2,NULL);
jreturn = pthread_join(tid1,NULL);
//jreturn = pthread_join(tid2,NULL);
printf("After thread call\n");
}
void* pfun1(void *vargp){
int i;
for(i=0;i<5;i++){
printf("Thread1: %d\n",i);
sleep(1);
}
return (void*)0;
}
void* pfun2(void *vargp){
int i;
for(i=5;i<10;i++){
printf("Thread2: %d\n",i);
sleep(1);
}
return (void*)0;
}
In the above program, I joined only the first thread to the main program using pthread_join(). And the second thread is only created and not attached to main. But output function contains the output of the second thread too. How come it is possible to get the output of 2nd thread even though it is not attached to main?
Output:
Before thread call
Thread2: 5
Thread1: 0
Thread2: 6
Thread1: 1
Thread2: 7
Thread1: 2
Thread2: 8
Thread1: 3
Thread2: 9
Thread1: 4
After thread call