In this post, we will discuss the Daemon threads in Python.
Daemon Threads
There are cases in the real world when you would require the threads in your program to run continuously to satisfy the clients and their customers. For instance, you would need any internet server to be constantly running so that any user can access your web application anytime. The same concept applies to the garbage collector, which runs continuously and deletes the variables that are no longer used. Such threads which run continuously are called ‘Daemon Threads,’ and we use them primarily to run the background tasks.
#Python program to create a daemon thread
from threading import *
from time import *
#to display numbers from 1 to 7 one each after every second
def display():
for i in range(5):
print('Normal thread: ',end='')
print(i+1)
sleep(1)
#to display date and time every 2 seconds
def display_time():
while True:
print('Daemon Thread: ',end='')
print(ctime())
sleep(2)
#create an ordinary thread and tag it to the display() and run it
t = Thread(target=display)
t.start()
#create another thread and tag it to the display_time()
d = Thread(target=display_time)
#make the thread daemon
d.daemon = True
#run the daemon thread
d.start()
d.join()
Output:
Normal thread: 1
Daemon Thread: Sun Nov 6 21:54:47 2022
Normal thread: 2
Daemon Thread: Sun Nov 6 21:54:49 2022
Normal thread: 3
Normal thread: 4
Daemon Thread: Sun Nov 6 21:54:51 2022
Normal thread: 5
Daemon Thread: Sun Nov 6 21:54:53 2022
Daemon Thread: Sun Nov 6 21:54:55 2022
Daemon Thread: Sun Nov 6 21:54:57 2022
Daemon Thread: Sun Nov 6 21:54:59 2022
Daemon Thread: Sun Nov 6 21:55:01 2022
Daemon Thread: Sun Nov 6 21:55:03 2022
Daemon Thread: Sun Nov 6 21:55:05 2022
In the above program, we created a common thread that runs for every second and displays the count until it reaches 5. We also created another thread which is a Python Daemon thread that keeps running forever. If you remove the join() method in the program above, the program’s execution will end immediately after the regular thread’s execution completes, as we won’t be waiting for the daemon thread to complete its execution in that case.
However, since our program has the join() method, the program’s execution was never-ending, and we had to use the CTRL+C to quit the execution forcibly.
You can use this concept of Daemon threads and tweak it based on the requirements of your project work to keep any action always running. We hope you have understood the concept of Python Daemon threads. Share your reviews in the comments section below. We would love to hear from you.