Daemon Threads
What is a daemon thread?
A daemon thread is a background thread.
- If only daemon threads are left running, Python can exit.
- Non-daemon threads keep the program alive.
Example
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")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")When to use daemon threads
- logging/reporting loops
- background monitoring
When NOT to use them
Donβt use daemon threads for work that must finish (e.g., writing critical data).
π§ͺ Try It Yourself
Exercise 1 β Create a Daemon Thread
Exercise 2 β Non-Daemon vs Daemon
Exercise 3 β Main Thread is Not a Daemon
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
