Detached thread¶
Category: Units of execution · Status: stub · Lessons: chapter 01, Threads
One line: A thread nobody will join: its result is unreachable, its end is unobserved, and whatever it borrowed must outlive it by some other argument.
Also called: detach, fire and forget.
How it connects¶
flowchart LR
n_detached_thread["Detached thread"]
n_task_leak["Leaked tasks"]
n_scoped_thread["Scoped thread"]
n_thread["Thread"]
n_detached_thread -->|can cause| n_task_leak
n_detached_thread ---|vs| n_scoped_thread
n_detached_thread -->|is a| n_thread
classDef center stroke-width:3px
class n_detached_thread center
classDef outside stroke-dasharray: 4 3
class n_task_leak,n_scoped_thread,n_thread outside
- Is a kind of: Thread
- Can lead to: Leaked tasks
- Often confused with: Scoped thread
- See also: Daemon and detached threads, Object lifetime
In each language¶
| Rust | Dropping a JoinHandle ↗ detaches its thread; the 'static bound on thread::spawn ↗ is what makes that safe |
| Go | Every goroutine is detached: a go statement ↗ yields no handle, and a sync.WaitGroup or a channel is how a program waits |
| C | pthread_detach ↗ marks a thread unjoinable and lets its storage be reclaimed as it ends |
| C++ | std::thread::detach ↗; a std::thread destroyed while still joinable calls std::terminate ↗ |
| Python | Thread(daemon=True) ↗ is not waited for at exit |
Where to read more¶
- In this library: Who waits when main returns?
- In this library: Can a thread borrow a local variable?
- Reference: POSIX: pthread_detach ↗