Python 尝试捕获未在子线程中工作
我有一个线程运行Python 尝试捕获未在子线程中工作,python,multithreading,Python,Multithreading,我有一个线程运行而true循环: from threading import Thread, Event class MyThread(Thread): def __init__(self, thread_id, name, counter, thread_func): Thread.__init__(self) self.thread_id = thread_id self.name = name self.counte
而true
循环:
from threading import Thread, Event
class MyThread(Thread):
def __init__(self, thread_id, name, counter, thread_func):
Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.counter = counter
self.thread_func = thread_func
self._stop_event = Event()
def run(self):
try:
while True:
self.thread_func()
except KeyboardInterrupt:
print 'keyboard interrupt'
self.stop()
def stop(self):
"""
stops the thread
"""
self._stop_event.is_set()
目标是捕获
键盘中断
事件并停止线程。但是,我无法执行,除了带有中断的
块。但是,当我将这个try/catch放在主线程上时,它就工作了。我做错了什么?子线程未接收到键盘中断。您可以在主线程中捕获异常并执行回调,例如,终止子线程。
下面是一个示例代码,举例说明:
import threading
if __main__ == "__name__":
t1 = threading.Thread()
t2 = threading.Thread()
try:
t1.start()
t2.start()
except KeyboardInterrupt as e:
t1.join()
t2.join()
哎呀!假设是
join
:)