Python Daemon Thread With Examples

In this tutorial we will be learning about Python Daemon Thread. In our previous tutorial we learned about Python getattr() function.

Python Daemon Thread

To start with this tutorial, you should have basic knowledge about threads. Basically there are two types of thread. One is daemon thread. Another is non-daemon thread.

While a non-daemon thread blocks the main program to exit if they are not dead. A daemon thread runs without blocking the main program from exiting. And when main program exits, associated daemon threads are killed too.

Python daemon thread example

We have a simple program where we are creating two threads. One of them will take longer time to execute because we have added sleep of 2 seconds. Let’s run the below program and observe the output.

You will get output like below.

So both the threads executed and then main thread exits and terminates the program.

Now we will make Thread a as a daemon thread. Then you will see the difference in output. So, let’s edit the previous code as following.

Notice the extra argument daemon=True while creating Thread a. This is how we specify a thread as daemon thread. Below image shows the output by the program now.

Python Daemon

Notice that program exits even though daemon thread was running.

When Daemon Threads are useful

In a big project, some threads are there to do some background task such as sending data, performing periodic garbage collection etc. It can be done by non-daemon thread. But if non-daemon thread is used, the main thread has to keep track of them manually. However, using daemon thread the main thread can completely forget about this task and this task will either complete or killed when main thread exits.

Note that you should use daemon thread only for non essential tasks that you don’t mind if it doesn’t complete or left in between.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: