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 join
ing another thread -- especially not totally useless blocking calls, such as join
ing 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;-).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…