gpt4 book ai didi

python - 如何阻止函数在事件循环中完成其代码

转载 作者:行者123 更新时间:2023-12-01 01:12:06 24 4
gpt4 key购买 nike

我有异步运行该函数的事件循环。然而,该函数会生成大量数据,因此当程序访问该函数时,执行时间会有点长。我还实现了一个停止按钮,因此即使事件循环尚未完成,应用程序也会退出该功能。问题是如何立即退出该函数或如何终止 asyncio 中的线程。

我已经尝试在函数中使用标志,但函数的执行速度足够快,可以在用户单击停止按钮之前检查标志。简而言之,线程已经在后台运行。

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

def stop_function(self):
if self._executor:
self._executor.shutdown(wait=False)
self.loop.stop()
self.loop.close()

我提供的代码是否有错误或缺失?预期的输出应该是,如果我单击停止按钮,程序最后不会生成数据。

最佳答案

您可以使用 threading.Event 将其传递给您的阻塞函数

event = threading.Event()
future = loop.run_in_executor(executor, blocking, event)
# When done
event.set()

阻塞函数只需要检查 is_set ,当你想停止它时,只需像上面那样调用 event.set() 即可。

def blocking(event):
while 1:
time.sleep(1)
if event.is_set():
break

关于python - 如何阻止函数在事件循环中完成其代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54757721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com