我正在运行需要时间才能完成的功能。用户可以选择停止此功能/事件。是否有一种简单的方法来停止线程或循环?
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
我想在用户单击停止按钮时尽快停止该功能,而不是等待完成其工作。
提前致谢!
是否有一种简单的方法来停止线程或循环?
你不能强行停止一个线程。要实现取消功能,您的函数将需要接受should_stop
参数,例如threading.Event
的实例,并偶尔检查它是否已设置。
如果你真的需要强制停止,并且如果你的函数可以通过multiprocessing在一个单独的进程中运行,你可以在一个单独的进程中运行它并在它应该停止时终止进程。有关asyncio上下文中的方法的详细说明,请参阅this answer。