【发布时间】:2017-07-03 23:58:16
【问题描述】:
我有如下 Python 多线程程序。如果我在 5 秒(大约)内按 ctrl+c,它将进入 KeyboardInterrupt 异常。
运行代码超过 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)
【问题讨论】:
标签: python multithreading python-2.7 keyboardinterrupt