Auto kill Python threads on exit
A standard multithreaded Python code goes something like this:
from time import sleep from threading import Thread from datetime import datetime def function(sleep_time): print("Current Time:", datetime.utcnow()) print("Sleeping...") sleep(sleep_time) print("Woke") print("Current Time:", datetime.utcnow()) thread = Thread(target=function, args=(2,)) thread.start() # thread.join() # This is the default so its not needed
Current Time: 2022-02-06 11:04:06.673492 Sleeping... Woke Current Time: 2022-02-06 11:04:08.675964
But not always do we need to join threads before exit as its a blocking
operation and its fine to automatically stop some threads. The main thread by
default joins all threads on exit. For this reason we have daemon
parameter
while creating Thread
object which doesn’t need to be joined and is instantly
killed on exit.
thread = Thread(target=function, args=(2,), daemon=True) thread.start()
Current Time: 2022-02-06 11:04:06.673492 Sleeping...
Quoting from Python 3 threading documentation:
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.
Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
For further reference: