如何停止多个线程 python

huangapple go评论69阅读模式
英文:

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. 使用此逻辑来取消标准线程:

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

huangapple
  • 本文由 发表于 2023年4月11日 01:32:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定