Search code examples
pythonpython-multithreading

Threading Set Daemon not working


A very simple script.

test.py

import temp
temp.start()

temp.py

import threading, time
f=open("output.txt","w")
def temp():
    for i in range(5):
        f.write(str(i))
        time.sleep(5)
    f.close()
def start():
    t=threading.Thread(target=temp)
    t.setDaemon(True)
    t.start()

I expected Daemon thread to complete as main process test.py exits immediately.But the daemon thread exits with the main and does not act like a daemon.Am i missing something basic here?


Solution

  • This is described in some detail in the python documentation at

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

    The most relevant bits are:

    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.

    and

    Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly.

    The overloading of the term 'daemon' and the negation contortions can make this a bit confusing but it what it boils down to is: A python program exits only after all of its threads complete, except for daemon threads which are simply terminated if no other non-daemon threads are left. In your case, that means the program exits killing your daemon thread before it has a chance to do anything (or, conversely, does not exit until your thread completes, if you setDaemon(false)).