Make each thread, except the main thread, a daemon ( t.daemon = True in 2.6 or better, t.setDaemon(True) in 2.6 or less, for each stream object t , before you start it). Thus, when the main thread receives KeyboardInterrupt, if it does not catch it or does not catch it, but decides to stop it anyway, the whole process will end. See documents .
edit : just seeing the OP code (not originally published) and the statement that “this does not work”, it looks like I should add ...:
Of course, if you want your main thread to remain responsive (for example, to control C), do not do this in blocking calls, such as join another thread, especially not completely useless blocking calls, such as join ing daemon threads. For example, just change the final loop in the main thread from the current one (without loss and damage):
for i in range(0, thread_count): threads[i].join()
to something more reasonable, for example:
while threading.active_count() > 0: time.sleep(0.1)
if your main task has nothing better than for all threads that should complete independently, or to gain control of C (or another signal).
Of course, there are many other applicable patterns, if you prefer that your threads do not interrupt suddenly (as there may be demonic threads) - if they also do not get bogged down permanently in unconditionally blocking calls, deadlocks, etc .; -.)
Alex Martelli Oct 28 '09 at 3:47 2009-10-28 03:47
source share