Home | Projects | Notes > Multi-Threading (POSIX Threads) > Joinable & Detached Threads

Joinable & Detached Threads

 

By using pthread_create() API, we can specify the thread to be created in one of the following two modes:

 

Joinable Threads

 

joinable-thread

 

Resources of the joinable thread are not released until it joins the parent thread. Therefore, it would be a wrong design if a thread is created in a joinable mode and it never has a chance to join some other thread that is blocked at the joint point.

A joinable thread can be converted into detached thread while it is running, or vice versa.

If no mode is specified upon the thread creation, the thread will run on joinable mode by default.

A Joinable thread may return the result to the parent (joinee) thread at the time of joint.

Example

Try and change the second argument of thread_create() for thread 2 and 3 and monitor the result. You should be able to predict the result correctly.

 

joinable-thread-example-visualized

 

Whom to Join?

A child joinable thread upon termination joins all the threads which are blocked on pthread_join() on former's thread handle (pthread_t).

Any thread as well as the parent thread can invoke pthread_join() to wait on any other joinable thread's termination. (Any thread can wait for the termination of any other joinable thread in the process).

Just note that pthread_join() cannot wait on detached thread's termination.

 

any-thread-can-pthread-joi

 

 

Detached Threads

 

detached-thread

 

Resources of the detached thread are released as soon as the thread terminates.

A detached thread can be converted into a joinable while it is running, or vice versa.

A detached thread does not return any result to its parent thread. It does its job and then terminate without notifying any other threads.

 

When to Create Joinable / Detached Threads?

Create thread T as joinable when:

Create thread T as detached when:

 

 

References

Sagar, A. (2022). Part A - Multithreading & Thread Synchronization - Pthreads [Video file]. Retrieved from https://www.udemy.com/course/multithreading_parta/