我有如下的Python多線程程序。如果我在5秒鐘內(大約)按ctrl + c,它會進入KeyboardInterrupt異常。Python線程在Python中按ctrl-c退出
運行超過15秒的代碼未能響應ctrl + c。如果我在15秒後按ctrl + c,它不起作用。這是不扔KeyboardInterrupt異常。可能是什麼原因 ?我在Linux上測試了這個。
#!/usr/bin/python
import os, sys, threading, time
class Worker(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# A flag to notify the thread that it should finish up and exit
self.kill_received = False
def run(self):
while not self.kill_received:
self.do_something()
def do_something(self):
[i*i for i in range(10000)]
time.sleep(1)
def main(args):
threads = []
for i in range(10):
t = Worker()
threads.append(t)
t.start()
while len(threads) > 0:
try:
# Join all threads using a timeout so it doesn't block
# Filter out threads which have been joined or are None
threads = [t.join(1) for t in threads if t is not None and t.isAlive()]
except KeyboardInterrupt:
print "Ctrl-c received! Sending kill to threads..."
for t in threads:
t.kill_received = True
if __name__ == '__main__':
main(sys.argv)