我正在运行需要时间才能完成的功能。用户可以选择停止此功能/事件。有没有一种简单的方法来停止线程或循环?
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 https://docs.python.org/3/library/threading.html#threading.Event,偶尔检查是否已设置。
如果您确实需要强制停止,并且您的函数可以通过以下方式在单独的进程中运行多重处理 https://docs.python.org/3.7/library/multiprocessing.html,您可以在单独的进程中运行它,并在应该停止时终止该进程。看这个答案 https://stackoverflow.com/a/52938384/1600898在 asyncio 的背景下详细阐述该方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)