Here is the code (adapted from www.cs.cmu.edu):
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread1, NULL);
printf("1\n");
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
sleep(5);
}
The output is:
Thread 1
Thread 2
1
Thread 1 returns: 0
Thread 2 returns: 0
The first two lines are displayed instantaneously. After a pause, last three lines are displayed. I thought that pthread_join(thread1, NULL) would have waited until thread1 was completed so there should have been a pause after the display of the first line and the output should have been:
Thread 1
1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
Why? Because the man page of pthread_join says: "The pthread_join() function waits for the thread specified by thread to terminate." How to explain the output? Something simple that I am missing.