- Joining and Detaching Threads.
- The main program must wait for the threads to run to completion.
- ``Joining`` is one way to accomplish synchronization between threads.
- Function pthread_join which suspends execution of the calling thread until the specified thread terminates.
- A call to this function waits for the termination of the thread whose id is given by thread.
- A call to this function waits for the termination of the thread whose id is given by thread.
Figure 3:
Threads joining.
|
- On a successful call to pthread_join, the value passed to pthread_exit is returned in the location pointed to by ptr.
- On successful completion, pthread_join returns 0, else it returns an error-code.
- When a thread is created, one of its attributes defines whether it is joinable or detached.
- Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.
- The final draft of the POSIX standard specifies that threads should be created as joinable.
- To explicitly create a thread as joinable or detached, the attr argument in the
routine is used.
- Detaching:
- The pthread_detach() routine can be used to explicitly detach a thread even though it was created as joinable.
- If a thread requires joining, consider explicitly creating it as joinable (portability).
- If you know in advance that a thread will never need to join with another thread, consider creating it in a detached state (resources).
- Reentrant functions are those that can be safely called when another instance has been suspended in the middle of its invocation.
- All thread functions must be reentrant because a thread can be preempted in the middle of its execution.
- If another thread starts executing the same function at this point, a non-reentrant function might not work as desired.
Cem Ozdogan
2010-11-29