import sys
import time
import threading
class exThread(threading.Thread):
def __init__(self, threadId):
threading.Thread.__init__(self)
self.threadId = threadId
def run(self):
try:
while 1:
pass
except KeyboardInterrupt:
print "Ctrl-C caught by thread"
finally:
print "Thread's finally clause being executed"
sys.exit() # Same as thread.exit()
cond = True
def func():
pass
try:
th = exThread(1)
th.start()
while True:
if cond:
func()
except KeyboardInterrupt:
print "Ctrl-C caught by main thread"
sys.exit(0)
finally:
print "Executing the finally clause from main thread"
在执行上面的代码时,当我按 Ctrl-C 时,主线程在打印其 finally 子句后退出。现在,由于子线程是非守护进程,它仍然在try中运行:除了键盘中断块。但是,此子线程似乎不响应 Ctrl-C,即使它应该捕获键盘中断异常。为什么?
据
我所知,KeyboardInterrup
仅在主线程中提出。为了能够停止其他线程,请使它们不时检查事件,然后自愿退出。
另一种选择是将子线程标记为 daemon=True
,以便在主线程终止时自动终止:
th.daemon = True
延伸阅读:
- 守护程序线程
- 的工作原理 守护程序线程说明
- 而且,守护进程线程可能是有害的:http://joeshaw.org/2009/02/24/605/