According to the manual page:
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
So, as I understand, the calling process will block until the specified thread exit.
Now consider the following code:
pthread_t thrs[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; i++)
{
pthread_create(&thrs[i], NULL, thread_main, NULL);
}
pthread_join(thrs[0], NULL); /* will be blocked here */
pthread_join(thrs[1], NULL);
pthread_join(thrs[2], NULL);
/* ... */
pthread_join(thrs[NUMTHREADS - 1], NULL);
The calling thread will be blocked in the call to pthread_join(thrs[0], NULL)
, until thrs[0]
exit in some way. But how if another thread, for example, thrs[2]
call pthread_exit()
while we are blocked in the call to pthread_join(thrs[0], NULL)
? Do we have to wait for thrs[0]
to exit in order to receive the return value of thrs[2]
?
Yes - the main thread blocked on
thrs[0]
will not get the result fromthrs[2]
until afterthrs[[0]
andthrs[1]
have also exited.If you need more flexibility one option is to do something like having the threads post their results in a queue or signal in some other way that the thread needs to be joined. The main thread can monitor that queue/signal and get the necessary results (which could come from a
pthread_join()
that is done on the thread that is known to be completed from information int he queue/signal).