I will also add my few bits here, I think one of the reasons why daemon threads are confusing to most people(atleast they were to me) is because of the Unix context to the word dameon
.
In Unix terminology the word daemon
refers to a process which once spawned; keeps running in the background and user can move on to do other stuff with the foreground process.
In Python threading context, every thread upon creation runs in the background, whether it is daemon
or non-daemon
, the difference comes from the fact how these threads affect the main thread.
When you start a non-daemon
thread, it starts running in background and you can perform other stuff, however, your main thread will not exit until all such non-daemon
threads have completed their execution, so in a way, your program or main thread is blocked.
With daemon
threads they still run in the background but with one key difference that they do not block the main thread.
As soon as the main thread completes its execution & the program exits, all the remaining daemon
threads will be reaped. This makes them useful for operations which you want to perform in background but want these operations to exit automatically as soon as the main application exits.
One point to keep note of is that you should be aware of what exactly you are doing in daemon
threads, the fact they exit when main thread exits can give you unexpected surprises. One of the ways to gracefully clean up the daemon
threads is to use the Threading Events to set the event as an exit handler and check if the event is set inside the thread and then break from the thread function accordingly.
Another thing that confused about daemon
threads is the definition from python documentation.
The significance of this flag is that the entire Python program exits
when only daemon threads are left
In simple words what this means is that if your program has both daemon
and non-daemon
threads the main program will be blocked and wait until all the non-daemon
have exited, as soon as they exit main thread will exit as well. What this statement also implies but is not clear at first glance is that all daemon
threads will be exited automatically once the main threads exits.