Skip to content

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 coffee

Was this page helpful?

Let us know how we did