Search code examples
c++pthreadspthread-join

How to wait two pthreads?


Would any one please tell me what happens between the last two code lines

// Creating Server and Client threads
pthread_create(&serverThread, NULL, (void* (*)(void*))&Server,(void *)0);

pthread_create(&clientThread, NULL, (void* (*)(void*))&Client,(void *)1);

// Wait until serverThread exits
pthread_join( serverThread, NULL);

// Wait until clientThread exits
pthread_join( clientThread, NULL);

I want to wait them simultaneously. What if one of the two threads terminates/exits? What if server kept running in an infinite loop?


Solution

  • The first join - pthread_join(serverThread, NULL); will wait until serverThread terminates.

    The clientThread may or may not terminate during this time; if it terminates, it remains in zombie state until pthread_join(clientThread, NULL); gets called. pthread_join will return immediately in this case.

    If clientThread has not yet finished execution when pthread_join(clientThread, NULL); is called, it will wait again until clientThread terminates.