Hi, I am new to multi-threaded programming and have a question about pthreads.
This is the test code that I run and I don't understand its behaviour. Can someone throw some light on it please.
void *t1(void *args){
printf("returning from t1\n");
return;
}
void *t2(void *args){
printf("returning from t2\n");
return;
}
int main(){
pthread_t thread1,thread2;
int r1,r2;
r1=pthread_create(&thread1,NULL,t1,NULL);
r2=pthread_create(&thread2,NULL,t2,NULL);
pthread_join(thread1,NULL);
// pthread_join(thread2,NULL);
return 0;
}
The behaviour of this program is either of the 5 shown below
murtuza@murtuza:FFTW$ ./ptest
returning from t2
returning from t1
murtuza@murtuza:FFTW$ ./ptest
returning from t1
returning from t2
murtuza@murtuza:FFTW$ ./ptest
returning from t1
murtuza@murtuza:FFTW$ ./ptest
returning from t2
returning from t2
murtuza@murtuza:FFTW$ ./ptest
returning from t1
returning from t2
returning from t2
I don't understand the 4th and 5th output. Why is thread t2 executing twice? Of course, if I uncomment pthread_join(&thread2,NULL,t2,NULL)
the program will behave correctly but I am specifically interested in the case where only one thread joins the main() thread.
thanks, Mir