我去 Google 查了一下, Python 的线程实现有一些奇怪的行为。
比如,主线程如果 block 在 thread.join()上,是不能捕获消息的(可能和全局解释器锁有关)。
我拿 StackOverflow 上的一个不通的示例代码作了些修改,使 CTRL+C 可以成功工作了(这里在主线程中调用 signal.pause()等待 SIGINT , join()不行):
import signal, sys, threading, time
THREADS = []
def handler(signal, frame):
global THREADS
print "Ctrl-C.... Exiting"
for t in THREADS:
t.alive = False
sys.exit(0)
class thread(threading.Thread):
def __init__(self):
self.alive = True
threading.Thread.__init__(self)
def run(self):
n = 0
while self.alive:
n = n + 1
print("round %s" %n)
time.sleep(1)
pass
def main():
global THREADS
t = thread()
t.start()
THREADS.append(t)
signal.pause()
for t in THREADS:
t.join()
if __name__ == '__main__':
signal.signal(signal.SIGINT, handler)
main()
一些资料:
http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-programhttp://stackoverflow.com/questions/19652446/python-program-with-thread-cant-catch-ctrlchttp://stackoverflow.com/questions/631441/interruptible-thread-join-in-python