Understanding Daemon Threads in Python
Explore daemon threads in Python, which run background tasks that can be interrupted without affecting the main application. Learn the key difference between daemon and non-daemon threads, including how the program behavior changes based on whether any non-daemon threads are active.
Daemon Threads in Python
Daemon threads execute tasks in the background. These tasks are non-critical, meaning they can be interrupted or canceled without affecting the application.
A key difference between daemon and non-daemon threads is that the program will exit if only daemon threads are running. If at least one non-daemon thread is running, the program will not exit.
Comparison
Daemon | Non-daemon |
---|---|
A process will exit if only daemon threads are running (or if no threads are running). | A process will not exit if at least one non-daemon thread is running. |
Creating a Daemon Thread
To create a daemon thread, set the daemon
property to True
.
Syntax
t1 = threading.Thread(daemon=True)
If a thread object is created without any parameters, its daemon
property can also be set to True
before calling the start()
method.
Syntax
t1 = threading.Thread()
t1.daemon = True
Example
Example
from time import sleep
from threading import current_thread, Thread
# function to be executed in a new thread
def run():
# get the current thread
thread = current_thread()
# is it a daemon thread?
print(f'Daemon thread: {thread.daemon}')
# create a new thread
thread = Thread(target=run, daemon=True)
# start the new thread
thread.start()
# block for 0.5 sec for daemon thread to run
sleep(0.5)
Output
Daemon thread: True
Daemon threads can perform tasks in the background to support non-daemon threads. For example:
- Create a file that stores log information in the background.
- Perform web scraping in the background.
- Automatically save data into a database in the background.
Setting Daemon Status of Active Thread
If a running thread is configured to be a daemon, a RuntimeError
is raised.
Example
from time import sleep
from threading import current_thread, Thread
# function to be executed in a new thread
def run():
# get the current thread
thread = current_thread()
# is it a daemon thread?
print(f'Daemon thread: {thread.daemon}')
thread.daemon = True
# create a new thread
thread = Thread(target=run)
# start the new thread
thread.start()
# block for 0.5 sec for daemon thread to run
sleep(0.5)
Output
Exception in thread Thread-1 (run):
Traceback (most recent call last):
. . . .
. . . .
thread.daemon = True
^^^^^^^^^^^^^
File "C:\Python311\Lib\threading.py", line 1219, in daemon
raise RuntimeError("cannot set daemon status of active thread")
RuntimeError: cannot set daemon status of active thread