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

How to stop function from finishing its code in event loop

我有异步运行函数的事件循环。但是,该函数会生成大数据,因此当程序访问该函数时,执行时间会有点长。我还实现了一个停止按钮,因此即使事件循环尚未完成,应用程序也会退出该功能。问题是如何立即退出该函数或如何在 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