简体   繁体   English

函数会使用 asyncio.gather(create_task(task)) 运行两次吗

[英]Will functions run twice with asyncio.gather(create_task(task))

What will be happened, if I run:如果我运行会发生什么:

tasks = []
for item in items:
  tasks.append(asyncio.create_task(f(item)))

res = asyncio.gather(*tasks)

Will functions run twice?函数会运行两次吗? After create_task and after gathercreate_taskgather之后

First, note that you must await asyncio.gather() for them to run at all.首先,请注意,您必须等待asyncio.gather()才能运行它们。

Once that is fixed, the functions will run only once.一旦修复,这些功能将只运行一次。 create_task() submits them to the event loop. create_task()将它们提交给事件循环。 After that, they will run during the next await .之后,它们将在下一个await期间运行。 asyncio.gather() simply ensures that the calling coroutine awaits their completion. asyncio.gather()只是确保调用协程等待它们完成。 For example, this will run them in two portions:例如,这将分两部分运行它们:

tasks = []
for item in items:
  tasks.append(asyncio.create_task(f(item)))

await asyncio.sleep(1)   # here they are running for a second

res = await asyncio.gather(*tasks)  # here we wait for them to complete

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

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