Python Daemon Threads

Created with Sketch.

Python Daemon Threads

Summary: in this tutorial, you’ll learn about Python daemon threads and how to use them effectively.

Introduction to the Python daemon threads

In Python, every program has at least one thread called the main thread. To create a program that has more than one thread, you use the threading module. By using multiple threads in the program, you can execute tasks concurrently.

Sometimes, you may want to execute a task in the background. To do that you use a special kind of thread called a daemon thread.

By definition, daemon threads are background threads. In other words, daemon threads are threads that execute tasks in the background.

Daemon threads are helpful for executing tasks that support non-daemon threads in the program. For example:

  • Log information to a file in the background.
  • Scrap contents from a website in the background.
  • Auto-save the data into a database in the background

Creating a daemon thread

To create a daemon thread, you set the daemon to True in the Thread constructor:

t = Thread(target=f, deamon=True)

Code language: Python (python)

Alternatively, you can set the daemon property to True after creating the Thread‘s instance:

t = Thread(target=f)
t.deamon = True

Code language: Python (python)

A daemon thread example

The following example shows how to create a non-daemon thread that shows the number of seconds that the program has been waiting for:

from threading import Thread
import time

def show_timer():
count = 0
while True:
count += 1
time.sleep(1)
print(f'Has been waiting for {count} second(s)...')

t = Thread(target=show_timer, daemon=True)
t.start()

answer = input('Do you want to exit?\n')

Code language: Python (python)

How it works.

First, define a function show_timer() that displays the number of seconds that the program has been waiting for.

Second, create a new thread that executes the show_timer() function:

t = Thread(target=show_timer)

Code language: Python (python)

Third, start the thread:

t.start()

Code language: Python (python)

Finally, call the input() function to prompt users for an input:

answer = input('Do you want to exit?\n')

Code language: Python (python)

If you run the program, it’ll show the following output and run forever.

Do you want to exit?Has been waiting for 1 second(s)...
Has been waiting for 2 second(s)...
Has been waiting for 3 second(s)...
Has been waiting for 4 second(s)...
Y
Has been waiting for 5 second(s)...
Has been waiting for 6 second(s)...

Code language: Python (python)

To terminate the program, you need to kill the terminal.

The program runs indefinitely because the thread t is a non-daemon thread. The program needs to wait for all non-daemon threads to complete before it can exit.

Now, let’s turn the thread into a daemon thread:

from threading import Thread
import time

def show_timer():
count = 0
while True:
count += 1
time.sleep(1)
print(f'Has been waiting for {count} second(s)...')

t = Thread(target=show_timer, daemon=True)
t.start()

answer = input('Do you want to exit?\n')

Code language: Python (python)

If you run the program, input something, and hit enter, the program will terminate. For example:

Do you want to exit?
Has been waiting for 1 second(s)...
Y

Code language: Python (python)

The program terminates because it doesn’t need to wait for the daemon thread to complete. Also, the daemon thread is killed automatically when the program exits.

Daemon threads vs. non-daemon threads

The following table illustrates the differences between daemon and non-daemon threads:

Daemon ThreadsNon-daemon Threads
Thread creationt = Thread(target=f, daemon=True)t = Thread(target=f)
The program needs to wait before exitingNoYes
Kind of tasksNot critical like loggingCritical

Summary

  • A daemon thread is a background thread.
  • A daemon thread is useful for executing tasks that are not critical.
  • The program can exit and doesn’t need to wait for the daemon threads to be completed.
  • A daemon thread is automatically killed when the program exits.

Leave a Reply

Your email address will not be published. Required fields are marked *