In this tutorial, you will learn what are daemon threads in Python and how to set them up, you should have a basic knowledge about threads to follow up in this tutorial.
A daemon thread is a thread that dies whenever the main thread dies, it is also called a non-blocking thread. Usually, the main thread should wait for other threads to finish in order to quit the program, but if you set the daemon flag, you can let the thread do its work and forget about it, and when the program quits, it will be killed automatically.
This is useful for many scenarios, suppose you are doing some web scraping tasks, and you want to make a thread that alerts you in email whenever a new item is inserted in that particular website you're scraping.
Another example you may want to make a thread that watches for log files in your program, and alert you when a critical error is occured.
In the end of the tutorial, we'll share with you some tutorials that we found useful to use daemon threads in.
Now that you know what a daemon thread is, and you know it's useful, let's take a demonstration example, the following code initiates a non-daemon thread and start it, and then we end the main thread as well:
The func()
function should run forever, as we're setting True
as the condition of the while
loop. After we started that thread, we make a simple sleep in the main thread and exit the program.
However, if you run it, you'll see the program keeps running and won't allow you to exit (only if you close the window):
So the non-daemon thread is making the program refuses to exit until it's finished.
The following example initiates a daemon thread this time:
Now we pass daemon=True
to threading.Thread
class to indicate that it's a daemon thread, you can also access the daemon
attribute to True
or use the setDaemon(True)
method.
Let's execute the program:
This time once the main thread finishes its work, the daemon thread also gets killed automatically and exits the program.
Real Examples
Below are some of the tutorials in which we used daemon threads to accomplish our tasks:
- Making a Keylogger in Python: a daemon thread to send keylogs to our email or saves to a file.
- Making a Port Scanner in Python: multiple daemon threads to scan for ports.
- Brute Forcing FTP Servers with Python: multiple daemon threads to attempt an FTP login.
- Making a Chat Application in Python: a daemon thread that listens for upcoming messages from the network, and prints them to the console.