Skip to content

Daemon Threads

diagram a daemon thread does not get to finish mermaid
When the last non-daemon thread ends, the interpreter shuts down and kills every daemon thread wherever it happens to be -- no exception raised in it, no finally block run, no flush. That is right for a background heartbeat and wrong for anything writing a file.

A daemon thread is a background thread.

  • If only daemon threads are left running, Python can exit.
  • Non-daemon threads keep the program alive.
daemon_thread.py
import threading
import time
 
 
def background():
    while True:
        print("background working...")
        time.sleep(0.5)
 
 
t = threading.Thread(target=background, daemon=True)
t.start()
 
time.sleep(2)
print("Main thread exiting")
  • logging/reporting loops
  • background monitoring

Don’t use daemon threads for work that must finish (e.g., writing critical data).

sketch The moment the main thread exits p5.js
Two runs of the same worker, which needs one second and prints FINISHED at the end. The main thread starts it and immediately exits. Watch what happens at the instant main finishes: the non-daemon run keeps the process alive to the end, and the daemon run is cut off wherever it happens to be. Neither raises anything.
pch.quizTag pch.quizDefaultTitle
  1. A daemon thread is halfway through writing a file when the main thread finishes. What happens?

    pch.quizShowAnswer

    B — It is killed where it stands — no exception, no `finally`, no flush — Measured: the same worker printed FINISHED with `daemon=False` and printed nothing with `daemon=True`. Interpreter shutdown does not ask daemon threads to stop; it stops existing.

  2. When is a daemon thread the right choice?

    pch.quizShowAnswer

    B — When abandoning the work half-done is harmless — A heartbeat, a metrics poller or a cache warmer can be abandoned safely. Anything holding a lock, writing a file, or with a record in flight cannot.

  3. How do you make sure a worker thread finishes before the program exits?

    pch.quizShowAnswer

    B — Leave it non-daemon (the default) and `join()` it — A non-daemon thread keeps the process alive by itself; `join()` makes the wait explicit. There is no `stop()` — a thread must be asked to finish, usually via a `threading.Event` it checks.

  4. What is the cleanest way to tell a long-running thread to shut down?

    pch.quizShowAnswer

    B — Give it a `threading.Event` it checks periodically — Cooperative shutdown is the only reliable kind. The thread checks the flag at a point where stopping is safe, then unwinds normally — running its `finally` blocks.

Exercise 3 – Main Thread is Not a Daemon

Section titled “Exercise 3 – Main Thread is Not a Daemon”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading