Daemon and detached threads¶
Category: Units of execution · Status: stub · Lessons: chapter 01, Threads
One line: A thread that does not keep its program alive: when the program ends, the thread is stopped wherever it happens to be.
Also called: daemon thread, detached thread, background thread.
How it connects¶
flowchart LR
n_daemon_thread["Daemon and detached threads"]
n_thread["Thread"]
n_daemon_thread -->|is a| n_thread
classDef center stroke-width:3px
class n_daemon_thread center
classDef outside stroke-dasharray: 4 3
class n_thread outside
- Is a kind of: Thread
- See also: Goroutine, Join, Virtual thread
In each language¶
| Rust | Dropping a JoinHandle ↗ detaches its thread, and every thread ends when main does ↗ |
| Go | Every goroutine behaves this way: when main returns the program exits ↗, without waiting for other goroutines |
| C | pthread_detach ↗ means nobody will join the thread; after pthread_exit ↗ the process exits with status 0 once the last thread has ended |
| C++ | std::thread::detach ↗ lets the thread run on after its std::thread object is gone |
| Java | Thread.setDaemon ↗; the JVM does not wait for daemon threads, and virtual threads are always daemons |
| Python | daemon=True ↗; the interpreter waits for non-daemon threads, and daemon threads are stopped abruptly at shutdown |
| C# | Thread.IsBackground ↗: background threads do not keep a process running |
| Haskell | Every forkIO ↗ thread is daemonic: the program ends when the main thread does, and waiting for the others is written by hand, for instance with an MVar |
Where to read more¶
- In this library: Who waits when main returns?
- In a sibling library: Go:
maindoes not wait ↗ - In the books: Async Rust, Maxwell Flitton, Caroline Morton — ch. 3, 'Building Our Own Async Queues' → 'Running Background Processes'
- In the books: Parallel Programming and Concurrency with C# 10 and .NET 6, Alvin Ashcraft — ch. 4, 'User Interface Responsiveness and Threading' → 'Leveraging background threads'
- In the books: The Go Programming Language Phrasebook, David Chisnall — ch. 9, 'Goroutines' → 'Performing Actions in the Background'
- In the books: The Linux Programming Interface, Michael Kerrisk — ch. 29, 'Threads: Introduction' → 'Detaching a Thread'
- In the books: Pthreads Programming, Bradford Nichols, Dick Buttlar, Jacqueline Proulx Farrell — ch. B, 'Pthreads Draft 4 vs. the Final Standard' → 'Detaching a Thread'