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.
I thought that pthread_join(thread1, NULL) would have waited until thread1 was completed
The above is correct; it will.
so there should have been a pause after the display of the first line
This part doesn't follow. You started both threads running, so both threads execute independently of (a.k.a. "in parallel with") each other, and independently of what the main thread is doing. That means that both threads will print out their "Thread X" line right away, and then both threads will wait 5 seconds before exiting. Meanwhile, the main thread will be waiting around five seconds for thread 1 to exit, then the main thread will print "1", then it will wait for thread 2 to exit (which shouldn't take long since thread 2's 5-second-delay will expire at around the same time as thread 1's 5-second-delay)