What does sys.exit really do with multiple threads?

(Paraphrasing what’s in the Python 2 documentation for Thread Objects)

Normally a Python program exits only when there’s nothing but daemon
threads (ignoring itself) left running. The “main thread” object which corresponds to the initial thread of control in the program isn’t a daemon thread. Threads created using threading.Thread inherit their daemonic status from the creating thread, so if that’s the main thread, they will also be non-daemonic.

This means that by default any threads created and started by your main program will prevent it from exiting if they are still running when the main thread is terminated (by sys.exit() or simply by just hitting the end of its code). In other words, the program exits only when no alive non‑daemon threads (i.e. only daemon threads) are left.

You can override this default behavior by explicitly setting✶✶ the
daemon property of any
created thread objects to True before starting it.

if __name__=="__main__":
    t = threading.Thread(target=threadrun)
    t.daemon = True  # Explicitly set property.
    t.start()
    sys.exit()

Which will allow the program to actually end when sys.exit() is called (although calling it explicitly like that would not be necessary since presumably the code above would be at the end of the script anyway).


A daemon thread is one that runs in the background and does not prevent the interpreter from exiting. See Daemon Threads Explanation.

✶✶ In Python 3.3, a daemon keyword argument with a default value of None was added to the Thread
class constructor
which means that, starting from that version onwards, you can simply use:

    # Sets whether the thread is daemonic via "daemon" keyword argument.
    t = threading.Thread(target=threadrun, daemon=True)

However, doing it separately via an explicit attribute assignment statement
still works, and would therefore be the more version-portable way of
doing it.

Leave a Comment