Skip to content

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

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