Open In App

Regular Threads vs Daemon Threads in Python

Last Updated : 14 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Output
Regular thread

Explanation:

  • 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

Output
regular threads vs daemon threads

Explanation:

  • 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.

Next Article
Practice Tags :

Similar Reads