简体   繁体   English

asyncio.create_task 装饰器不会同时执行

[英]asyncio.create_task decorator doesn't execute concurrently

I have having some trouble understanding asyncio's create_task function.我在理解 asyncio 的 create_task function 时遇到了一些麻烦。 From the documentation, tasks should be run concurrently when they are awaited.从文档中,任务应该在等待时同时运行。 I wrapped the async func in a deocrator so I don't have to create_task() for every async function.我将异步函数包装在一个 deocrator 中,因此我不必为每个异步 function 创建任务()。 But the concurrent execution fails但是并发执行失败

  import asyncio
  import time


  def async_task(func):
      def wrapper():
          return asyncio.create_task(func())
      return wrapper


  @async_task
  async def bar() -> int:
      await asyncio.sleep(3)
      return "hello"


  @async_task
  async def foo() -> int:
      await asyncio.sleep(3)
      return "world"


  async def main() -> None:
      print(time.strftime('%X'))
      print(await bar())
      print(await foo())
      print(time.strftime('%X'))

  asyncio.run(main())

There's a difference between:两者之间有区别:

asyncio.create_task(async_fun())

and

await asyncio.create_task(async_fun())

The second one waits for the task to finish before going forward, so you're scheduling foo only after bar has finished.第二个在继续之前等待任务完成,因此您仅在 bar 完成后才安排 foo 。

First create tasks then await for them:首先创建任务,然后等待它们:

foo_task = foo()
bar_task = bar()
await foo_task
await bar_task

Or use asyncio.gather或者使用asyncio.gather

await asyncio.gather(foo(), bar())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM