如何在执行程序中停止循环 运行?
How to stop loop running in executor?
我是 运行 需要时间才能完成的函数。用户可以选择停止此 function/event。有没有简单的方法来停止线程或循环?
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
我想在用户单击停止按钮时尽快停止功能,而不是等待完成它的工作。
提前致谢!
Is there an easy way to stop the thread or loop?
您不能强行停止线程。要实现取消功能,您的函数需要接受一个 should_stop
参数,例如 threading.Event
的实例,并偶尔检查它是否已设置。
如果您确实需要强制停止,并且您的函数可以通过 multiprocessing, you can run it in a separate process and kill the process when it is supposed to stop. See 在单独的进程中运行,以便在 asyncio 的上下文中详细说明该方法。
我是 运行 需要时间才能完成的函数。用户可以选择停止此 function/event。有没有简单的方法来停止线程或循环?
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
我想在用户单击停止按钮时尽快停止功能,而不是等待完成它的工作。
提前致谢!
Is there an easy way to stop the thread or loop?
您不能强行停止线程。要实现取消功能,您的函数需要接受一个 should_stop
参数,例如 threading.Event
的实例,并偶尔检查它是否已设置。
如果您确实需要强制停止,并且您的函数可以通过 multiprocessing, you can run it in a separate process and kill the process when it is supposed to stop. See