Terminate a multi-thread python program

Make every thread except the main one a daemon (t.daemon = True in 2.6 or better, t.setDaemon(True) in 2.6 or less, for every thread object t before you start it). That way, when the main thread receives the KeyboardInterrupt, if it doesn’t catch it or catches it but decided to terminate anyway, the whole process will terminate. See the docs.

edit: having just seen the OP’s code (not originally posted) and the claim that “it doesn’t work”, it appears I have to add…:

Of course, if you want your main thread to stay responsive (e.g. to control-C), don’t mire it into blocking calls, such as joining another thread — especially not totally useless blocking calls, such as joining daemon threads. For example, just change the final loop in the main thread from the current (utterless and damaging):

for i in range(0, thread_count):
    threads[i].join()

to something more sensible like:

while threading.active_count() > 0:
    time.sleep(0.1)

if your main has nothing better to do than either for all threads to terminate on their own, or for a control-C (or other signal) to be received.

Of course, there are many other usable patterns if you’d rather have your threads not terminate abruptly (as daemonic threads may) — unless they, too, are mired forever in unconditionally-blocking calls, deadlocks, and the like;-).

Leave a Comment