Search code examples
pythonmultithreadingconcurrencydaemonexit

Daemon threads - When does a python app finish running?


I found this in the python documentation. https://docs.python.org/3/library/threading.html#threading.Thread.daemon

The entire Python program exits when no alive non-daemon threads are left.

Does this mean that a python application terminates when there are literally only daemon threads left? Or am I misunderstanding

import threading
import time

def daemonThread():
    while True:
        print("Sending Out Heartbeat Signal")
        time.sleep(2)
        
if __name__ == '__main__':
        daemonThread = threading.Thread(target=daemonThread)
        daemonThread.daemon = True
        daemonThread.start()
        print('finish')

Output:

Sending Out Heartbeat Signal
finish

In this example, my program quickly ends up ignoring the daemon thread even when it has an infinite loop.


Solution

  • Daemon threads do not stop a Python program running

    So yes, when all that is left is daemon threads, the program stops.

    It hasn't ignored the daemon thread, it has simply killed it, as expected.

    https://docs.python.org/3/library/threading.html

    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.

    Use daemon threads for things you want to last as long as the non-daemon part of your program is running

    ... but be unceremoniously killed as soon as it is over.