2
votes

According to the documentation: 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.

Sample code:

thread = threading.Thread(target=MultiHandler().network, args=(conn, data), daemon=True)
thread.start()

Refering to many other StackOverflow answers, it is not clear to me if daemon threads are forced to close when the main thread calls sys.exit()

1
When a program exits, all of its children threads are killed with it. Threads that are not daemonic will prevent the program from exiting, hence preventing their own destruction. - zwer
@zwer In that case if my threads are non-daemon do I still have to call join() to wait for the thread before calling sys.exit()? - X3Gamma
You don't, but then you lose control over your program exit. If you don't manage graceful exit you'll end up with your main thread finishing and then hanging there waiting for other threads to finish with no way to instigate that. - zwer
Documentation for sys.exit() is less than clear about multi-threaded programs, but if you look closely, you'll see that it says that sys.exit() doesn't do anything but throw an exception. So, it will only terminate the one thread that calls it, and only if the thread has no handler that swallows the exception. - Solomon Slow

1 Answers

1
votes

Referring to the comment posted by zwer,

When a program exits, all of its children threads are killed with it. Threads that are not daemonic will prevent the program from exiting, hence preventing their own destruction. - zwer

In short, yes daemon threads will not stop the program from exiting thus they will be killed on exit.