我的程序中有2个线程,我希望在键盘中断上停止,但我不知道如何做到这一点。其中一个线程有一个while循环,而另一个线程只是一个函数,它调用了一个充满函数的类。请帮忙,谢谢。
停止程序
这很简单,你只需要杀死线程
#Start a new thread
t = multiprocessing.Process(target = func)
t.start()
#Kill the thread
t.kill()
你可以使用KeyboardInterrupt来捕获CTRL+C输入并杀死线程。
t = None
try:
t = multiprocessing.Process(target = func)
t.start()
except KeyboardInterrupt:
t.kill()
print("stopping")
我使用这个逻辑来取消标准的线程:
1。MainThread
- 我在主进程/线程中运行键盘输入 我可以通过threading.Event().set()设置事件
- 参见
class MainThread(threading.Thread)
的代码示例
def __init__(self, *args, **kwargs): super(StoppableThread, self).__init__(*args, **kwargs) self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set()
2。BackgroudThreads
- 后台线程正在(周期性地)检查这个信号状态,并可以关闭它们的执行。
BTW:很好的澄清见文章