英文:
How to stop multiple threads python
问题
我有2个线程在我的程序中,我希望在键盘中断时停止它们,但我不知道该怎么做。其中一个线程有一个while循环,另一个只是一个调用了一堆函数的函数。请帮忙,谢谢。
停止程序
英文:
I have 2 threads in my program that I wish to stop on keyboard interrupt but I dont know how to do it. One of the threads has a while loop and the other is just a function which calls a class full of functions. Please help thank you.
Stopping the program
答案1
得分: 1
只需终止线程
# 启动一个新线程
t = multiprocessing.Process(target=func)
t.start()
# 终止线程
t.kill()
英文:
it's simple you have only to kill thread
#Start a new thread
t = multiprocessing.Process(target = func)
t.start()
#Kill the thread
t.kill()
答案2
得分: 1
你可以使用 KeyboardInterrupt 来捕捉 CTRL+C 输入并杀死线程。
t = None
try:
t = multiprocessing.Process(target=func)
t.start()
except KeyboardInterrupt:
t.kill()
print("stopping")
英文:
You can use KeyboardInterrupt to catch CTRL+C input and do kill threads.
t = None
try:
t = multiprocessing.Process(target = func)
t.start()
except KeyboardInterrupt:
t.kill()
print("stopping")
答案3
得分: 0
- 使用此逻辑来取消标准线程:
1. 主线程
- 我在主进程/线程中从键盘输入
- 我可以通过
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. 后台线程
- 后台线程定期检查此信号状态并可以关闭它们的执行。
顺便说一句:详细说明请参阅文章
英文:
I am using this logic for standard thread canceling:
1. MainThread
- I run input from keyboard in main process/thread
- I can setup event via threading.Event().set()
- See code sample for
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
- Background threads are checking (periodically) this signal state and can close their execution.
BTW: nice clarification see article
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论