Python:有没有办法检查“是否请求停止”?在线程中的每一行之前?
我希望能够同时中断多个线程。一种解决方案可能是:
stop_all_threads = False
def abort_if_requested():
global stop_all_threads
if stop_all_threads:
raise Exception()
def thread_target():
abort_if_requested()
do_some_work()
abort_if_requested()
do_more_work()
abort_if_requested()
last_work_piece()
my_thread = threading.Thread(target=thread_target)
my_thread.start()
...
stop_all_threads = True
但显然,遵循起来有点烦人,并且如果工作功能需要很长时间,也不会立即停止它们。有没有更简单的方法?我知道 multiprocessing.Process.terminate
但我必须在我的用例中使用 threading.Thread
,或者其他提供低延迟共享内存的方法。
I want to be able to interrupt many threads at once. One solution could be:
stop_all_threads = False
def abort_if_requested():
global stop_all_threads
if stop_all_threads:
raise Exception()
def thread_target():
abort_if_requested()
do_some_work()
abort_if_requested()
do_more_work()
abort_if_requested()
last_work_piece()
my_thread = threading.Thread(target=thread_target)
my_thread.start()
...
stop_all_threads = True
But obviously it's a bit annoying to follow and doesn't stop them immediately if the work functions take long. Is there a simpler way? I know about multiprocessing.Process.terminate
but I have to use threading.Thread
in my use case, or some other method that provides shared memory with low latency.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不太确定你在这里问什么,但这是我唯一能想到的:
尝试重新编码,因为我不太明白你在这里需要什么。
I'm not too sure what you're asking here but this is the only thing I can think of:
Try to recode this because I don't really understand what you needed here.
您可以传递
Event
来自threading
库的类作为线程目标函数的参数,并在您想要停止所有线程上的处理时设置它。当事件被设置时,while 循环将停止,线程将正常终止。我还建议您通过调用 < 等待线程终止
Thread
对象上的 code>join 方法。如果您需要处理结果,这可以确保结果可用并且线程终止。如果您使用多个线程,请对所有线程调用join
。You can pass the
Event
class fromthreading
library as an argument to the thread target function and set it when you want to stop processing on all threads. When the event will be set, while loops will stop and the thread will gracefully terminate.I also suggest you to wait for the thread to terminate by calling
join
method on yourThread
object. If you need the results from your processing, this ensures that the results are available and the thread terminated. If you're using multiple threads, calljoin
on all of them.