Blocking in pthread_join()

7.3k Views Asked by At

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]?

3

There are 3 best solutions below

0
On BEST ANSWER

Yes - the main thread blocked on thrs[0] will not get the result from thrs[2] until after thrs[[0] and thrs[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).

0
On

Yes. The code is executed in serial.

1
On

But how if another thread, say thrs[2] exit while we are blocked in the call to pthread_join(thrs[0], NULL)?

Yes, it could happen. In that case, pthread_join(thrs[2], NULL); will return immediately.

Do we have to wait for thrs[0] to exit in order to receive the return value of thrs[2]?

Yes, you have to wait for thr[0] to terminate.


(Not directly related to the question)

It's not necessary to call pthread_join() on every thread you create. It's a convenient function to get the return status from thread(s). If you don't need to know the termination status of the thread, you could create the thread by seeting the "detached" attribute or call pthread_detach(pthread_self()); from the thread itself to make it detached. In some cases, you would want the threads created to continue execution but no longer need the main thread. In that case, you could call pthread_exit(NULL); from main thread which will let other threads to continue even after main thread exits.