Multithreaded Programming Guide

pthread_join(3THR)

Use pthread_join(3THR) to wait for a thread to terminate.

Prototype:
int	pthread_join(thread_t tid, void **status);
#include <pthread.h>

pthread_t tid;
int ret;
int status;

/* waiting to join thread "tid" with status */
ret = pthread_join(tid, &status);

/* waiting to join thread "tid" without status */
ret = pthread_join(tid, NULL); 

The pthread_join() function blocks the calling thread until the specified thread terminates.

The specified thread must be in the current process and must not be detached. For information on thread detachment, see "Set Detach State".

When status is not NULL, it points to a location that is set to the exit status of the terminated thread when pthread_join() returns successfully.

Multiple threads cannot wait for the same thread to terminate. If they try to, one thread returns successfully and the others fail with an error of ESRCH.

After pthread_join() returns, any stack storage associated with the thread can be reclaimed by the application.

Return Values

Returns a zero when it completes successfully. Any other returned value indicates that an error occurred. When any of the following conditions are detected, pthread_join() fails and returns the corresponding value.


ESRCH

tid is not a valid, undetached thread in the current process.


EDEADLK

tid specifies the calling thread.


EINVAL

The value of tid is invalid.

The pthread_join() routine takes two arguments, giving you some flexibility in its use. When you want the caller to wait until a specific thread terminates, supply that thread's ID as the first argument.

If you are interested in the exit code of the defunct thread, supply the address of an area to receive it.

Remember that pthread_join() works only for target threads that are nondetached. When there is no reason to synchronize with the termination of a particular thread, then that thread should be detached.

Think of a detached thread as being the thread you use in most instances and reserve nondetached threads for only those situations that require them.