【问题标题】:Running functions in a thread class in the background with asyncio使用 asyncio 在后台线程类中运行函数
【发布时间】:2018-05-26 15:04:14
【问题描述】:

这是我第一次尝试在项目中使用asyncio。我希望我的类能够初始化并运行,它的几个函数会定期“在后台”运行。我希望类的 init 在启动这些后台任务后返回,以便它可以同时继续执行同步操作。

我有什么:

 class MyClass(threading.Thread):
  def __init__(self, param):
      self.stoprequest = threading.Event()
      threading.Thread.__init__(self)

      self.param = param

      self.loop = asyncio.new_event_loop()
      asyncio.set_event_loop(self.loop)
      asyncio.ensure_future(self.periodic(), loop=self.loop)

      print("Initialized")

  async def periodic(self):
      while True:
          print("I'm here")
          await asyncio.sleep(1)

  def run(self):
       # continue to do synchronous things

毫无疑问,这行不通。我也尝试过在 init 中使用带有run_until_complete() 的“普通”asyncio 函数,但当然 init 永远不会返回。

如何在后台定期运行属于该类的asyncio 函数,而该类的其余部分 (run()) 继续进行同步工作?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    将循环作为参数传递给ensure_future 不会启动此循环。你应该调用run_until_completerun_forever 来强制你启动协程,没有别的办法。

    如何定期运行属于此类的 asyncio 函数 在后台,而类的其余部分 (run()) 继续做 同步工作?

    你不能。就像您不能在主线程中同时运行事件循环和同步代码一样。 Loop starting - 阻塞线程的执行流程,直到循环停止。这就是asyncio 的工作原理。

    如果您想在后台运行asyncio,您应该在单独的线程中运行它并在主线程中执行同步操作。如何做到这一点的例子可以找到here

    如果你需要在线程中运行阻塞代码和asyncio,现在最方便的方法是在主线程中运行asyncio,并使用run_in_executor函数在后台线程中运行阻塞代码。你可以找到这样做的例子here

    重要的是要说asyncio 本身通常用于主线程(没有其他线程)以实现异步编程的好处。你确定你需要第二个线程吗?如果不是,请阅读this answer 了解为什么使用asyncio

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多