Back
+15 XP
Concept

Daemon Threads: Background Workers

A daemon thread (`daemon=True`) runs in the background. Unlike normal threads that keep the process alive, Python terminates immediately when only daemon threads remain 👻.

python
import threading, time

def background_metrics():
    while True:
        time.sleep(0.1)

# Daemon thread dies instantly when main program exits:
t = threading.Thread(target=background_metrics, daemon=True)
t.start()

print(f"Thread is daemon: {t.daemon} 👻")

# 59. Daemon Threads: Background Workers A daemon thread (`daemon=True`) runs in the background. Unlike normal threads that keep the process alive, Python terminates immediately when only daemon threads remain 👻. ```python import threading, time def background_metrics(): while True: time.sleep(0.1) # Daemon thread dies instantly when main program exits: t = threading.Thread(target=background_metrics, daemon=True) t.start() print(f"Thread is daemon: {t.daemon} 👻") ``` Use daemon threads for heartbeats, cache eviction, or telemetry that should never prevent your CLI tool or application from shutting down cleanly! 👻 --- ### Question What occurs when the main thread finishes and only daemon threads are running? 🧠 - [ ] a. The Python process exits immediately, abruptly killing the daemon threads 👻 - [ ] b. The program waits forever until each daemon thread completes - [ ] c. The OS promotes daemon threads to root processes - [ ] d. A RuntimeError is raised by CPython --- ### Challenge Create a `threading.Thread(target=lambda: None, daemon=True)`. Print whether `thread.daemon` is `True`. 🎯 <details> <summary>Solution</summary> ```python import threading thread = threading.Thread(target=lambda: None, daemon=True) print(thread.daemon) ``` </details>

Checkpoint

What occurs when the main thread finishes and only daemon threads are running? 🧠

Practice

Create a `threading.Thread(target=lambda: None, daemon=True)`. Print whether `thread.daemon` is `True`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks