edit:
I made the wrong assumption that threads started running on pthread_join
when they actually start running on pthread_create
.
I'm learning to use Posix threads, and I've read that:pthread_join() - wait for thread termination
So, in the code sample, main's exit(0) is not reached until both started threads end.
But after the first call to pthread_join(), main continues executing, because the second call to pthread_join() actually runs, and the message in between is printed.
So how's this? does main continue executing while both threads aren't finished yet? or doesn't it?
I know this isn't a reliable way of testing, but the second test message always gets printed after both threads are finished, no matter how long the loop is. (at least on my machine when I tried it)
void *print_message_function( void *ptr )
{
char *message = (char *) ptr;
for( int a = 0; a < 1000; ++a )
printf( "%s - %i\n", message, a );
return NULL;
}
//
int main( int argc, char *argv[] )
{
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( "Let's see when is this printed...\n" );
pthread_join( thread2, NULL);
printf( "And this one?...\n" );
//
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
The function pthread_join
waits for the thread to finish or returns immediately if the thread is already done.
So in your case
pthread_join( thread1, NULL); /* Start waiting for thread1. */
printf( "Let's see when is this printed...\n" ); /* Done waiting for thread1. */
pthread_join( thread2, NULL); /* Start waiting for thread2. */
printf( "And this one?...\n" ); /* Done waiting for thread2. */
But after the first call to pthread_join(), main continues executing, because the second call to pthread_join() actually runs, and the message in between is printed.
False. pthread_join
waits unless thread1 is already done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With