Regular Threads vs Daemon Threads in Python
Last Updated :
14 May, 2025
In Python, multithreading enables concurrent execution of tasks. Two common types of threads are Regular Threads (Non-Daemon) and Daemon Threads. While both run in parallel, they behave differently when it comes to termination. Understanding these differences is important for writing efficient multithreaded programs.
What is a Regular Thread?
A Regular Thread (Non-Daemon Thread) runs independently and must complete its execution before the Python program can terminate. If the main program finishes, the interpreter will wait for all regular threads to complete their tasks before exiting. It's key characteristics include:
- Completion: A regular thread will keep running until its task finishes, and the Python interpreter will not exit until the thread completes.
- Blocking Behavior: The main program blocks and waits for regular threads to finish using methods like .join().
Example: In this example, even after the main program prints "Main program completed!", the interpreter waits for the regular thread to finish its task before exiting.
Python
import threading
import time
def task():
for i in range(5):
print(f"Thread is running: {i}")
time.sleep(1)
# Start thread
t = threading.Thread(target=task)
t.start()
# Wait for thread
print("Main program completed!")
t.join()
Output
Regular threadExplanation:
- task() loops 5 times, printing the iteration and sleeping for 1 second each time.
- threading.Thread(target=task) creates the thread, and t.start() begins execution.
- main() prints a message, then t.join() waits for the thread to finish before exiting.
What is a Daemon Thread in Python?
A Daemon Thread runs in the background and is automatically terminated when the main program exits, regardless of whether the daemon thread has finished its task. These threads are typically used for background tasks, such as monitoring or logging, where it doesn't matter if the thread is still running when the main program exits. It's key characteristics include:
- Completion: Daemon threads do not have to finish before the program exits. They are terminated when the main program finishes.
- Non-blocking: The main program does not wait for daemon threads to finish. They run in the background until the program ends.
Example: Here, the daemon thread is stopped automatically as soon as the main program exits, so you might not see all of the daemon thread's output.
Python
import threading
import time
def task():
for i in range(10):
print(f"Daemon thread running: {i}")
time.sleep(1)
# Start daemon thread
t = threading.Thread(target=task)
t.setDaemon(True)
t.start()
# Main program ends
print("Main program completed!")
Output
Daemon thread running: 0
Main program completed!
Explanation:
- task() loops 10 times, printing a message and pausing for 1 second per iteration.
- threading.Thread(target=task) creates a thread to run task().
- t.setDaemon(True) makes the thread a daemon that ends when the main program finishes.
- t.start() runs the task() function in the background.
- main() Prints "Main program completed!" and exits without waiting for the daemon thread.
Differences between Regular Threads and Daemon Threads
Understanding regular vs daemon threads is key in Python multithreading. Using them wisely ensures efficient and controlled concurrency. Let's understand this through the following table.
Feature | Regular Threads (Non-Daemon) | Daemon Threads |
---|
Completion | Must complete before program exits | Terminated when the main program exits |
---|
Purpose | Critical tasks | Background tasks |
---|
Main Program Waiting | Waits for regular thread to finish | Does not wait for daemon threads |
---|
Thread Lifecycle Control | Can be controlled (join, etc.) | Automatically terminated |
---|
Usage Example | Database transactions | Logging, monitoring |
---|
Resource Management | Requires explicit resource management | Automatically handles cleanup |
---|
Error Handling | Easier to handle exceptions | Harder to manage errors due to premature termination |
---|
Performance | May slow down program termination | More efficient in non-critical operations |
---|
When to Use Regular Threads vs Daemon Threads
Understanding when to use regular threads and daemon threads is crucial for writing efficient and predictable multithreaded programs. Each has distinct characteristics that make them suitable for different situations.
Use Regular Threads When:
- The task is critical and must be completed before the program terminates.
- You need to perform a task that might take a long time to finish, and it needs to be completed for the program's logic.
Use Daemon Threads When:
- The task is non-critical and can be safely interrupted if the main program exits.
- You need background tasks like logging or monitoring that should run as long as the program is alive but do not need to be completed when the program ends.
Combined Example: Regular and Daemon Threads
In this example, we show how to use both a regular thread, which waits for completion and a daemon thread, which runs in the background and stops when the main program exits.
Python
import threading
import time
# Regular thread task
def task_1():
for i in range(5):
print(f"Regular thread running: {i}")
time.sleep(1)
# Daemon thread task
def task_2():
while True:
print("Daemon thread running")
time.sleep(1)
# Create threads
a = threading.Thread(target=task_1)
b = threading.Thread(target=task_2)
b.daemon = True # Daemon
# Start threads
a.start()
b.start()
# Wait for regular thread
a.join()
print("Main program finished")
Output
regular threads vs daemon threadsExplanation:
- task_1() loops 5 times, prints "Regular thread running: {i}" and waits 1 second each time.
- task_2() runs indefinitely, printing "Daemon thread running" every second.
- b.daemon = True makes task_2 a daemon thread, which terminates when the main program finishes.
- a.start() starts the regular thread, b.start() starts the daemon thread.
- a.join() waits for the regular thread to finish before printing "Main program finished." The daemon thread stops automatically when the main program ends.
Related articles
Similar Reads
Python Daemon Threads
The threads that are always going to run in the background provide support to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background. This article is based o
6 min read
Start and stop a thread in Python
The threading library can be used to execute any Python callable in its own thread. To do this, create a Thread instance and supply the callable that you wish to execute as a target as shown in the code given below - Code #1 : Python3 1== # Code to execute in an independent thread import time def co
4 min read
Check if a Thread has started in Python
Problem: To know when will a launched thread actually starts running. A key feature of threads is that they execute independently and nondeterministically. This can present a tricky synchronization problem if other threads in the program need to know if a thread has reached a certain point in its ex
4 min read
Asyncio Vs Threading In Python
In Python, both Asyncio and Threading are used to achieve concurrent execution. However, they have different mechanisms and use cases. This article provides an in-depth comparison between Asyncio and Threading, explaining their concepts, key differences, and practical applications.Table of ContentKe
6 min read
Releasing GIL and mixing threads from C and Python
Releasing GIL in C extension: Give a C extension code and one needs to concurrently execute it with other threads in the Python interpreter. For this Global Interpreter Lock (GIL) has to be released and reacquired. Code #1 : Releasing and Reacquiring GIL by inserting following macros C #include
2 min read
How to use Thread in Tkinter Python
Prerequisite:Â Python GUI â tkintermultithreading Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is th
2 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception hand
3 min read
Python Falcon - Request & Response
Python Falcon, a nimble web framework, simplifies the process of building web APIs by efficiently managing incoming requests, which are messages asking for something from your API, and providing an easy way to create structured responses that Falcon then sends back to the requester, making it a swif
7 min read
Python | Different ways to kill a Thread
In general, killing threads abruptly is considered a bad programming practice. Killing a thread abruptly might leave a critical resource that must be closed properly, open. But you might want to kill a thread once some specific time period has passed or some interrupt has been generated. There are t
10 min read
How to create a new thread in Python
Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there
2 min read