如何停止在执行程序中运行的循环? [英] How to stop loop running in executor?

查看:60
本文介绍了如何停止在执行程序中运行的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行需要时间才能完成的功能.用户可以选择停止此功能/事件.有没有简单的方法来停止线程或循环?

I am running function that takes time to finish. The user has a choice to stop this function/event. Is there an easy way to stop the thread or loop?

class ThreadsGenerator:
    MAX_WORKERS = 5

    def __init__(self):
        self._executor = ThreadPoolExecutor(max_workers=self.MAX_WORKERS)
        self.loop = None
        self.future = None

    def execute_function(self, function_to_execute, *args):
        self.loop = asyncio.get_event_loop()
        self.future = self.loop.run_in_executor(self._executor, function_to_execute, *args)

        return self.future

我想在用户单击停止按钮时尽快停止该功能,而不是等待完成其工作.

I want to stop the function as quickly as possible when the user click the stop button, not waiting to finish its job.

提前致谢!

推荐答案

是否有一种简单的方法可以停止线程或循环?

Is there an easy way to stop the thread or loop?

您不能强行停止线程.要实现取消功能,您的函数需要接受 should_stop 参数,例如 threading.Event,偶尔检查是否已设置.

You cannot forcefully stop a thread. To implement the cancel functionality, your function will need to accept a should_stop argument, for example an instance of threading.Event, and occasionally check if it has been set.

如果您确实需要强制停止,并且您的函数可以通过 多处理,您可以在一个单独的进程中运行它并在它应该停止时终止该进程.请参阅此答案,了解在 asyncio 上下文中对该方法的详细说明.

If you really need a forceful stop, and if your function is runnable in a separate process through multiprocessing, you can run it in a separate process and kill the process when it is supposed to stop. See this answer for an elaboration of that approach in the context of asyncio.

这篇关于如何停止在执行程序中运行的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆