vks
vks

Reputation: 67968

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?

Upvotes: 4

Views: 4177

Answers (2)

complementing pvg's nice answer, a possible solution for your question is to use join(), in your case:

t.join()

More about join in "what is the use of join() in python threading"

A nice guide explaining in a practical way can be found at: https://realpython.com/intro-to-python-threading/

Upvotes: 0

pvg
pvg

Reputation: 2729

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)).

Upvotes: 3

Related Questions