如果我运行会发生什么
tasks = []
for item in items:
tasks.append(asyncio.create_task(f(item)))
res = asyncio.gather(*tasks)
函数会运行两次吗?create_task
之后和gather
之后
首先,请注意,您必须等待asyncio.gather()
才能运行它们。
一旦修复,函数将只运行一次。create_task()
将它们提交给事件循环。之后,它们将在下一个await
期间运行。asyncio.gather()
只是确保调用协同程序等待它们的完成。例如,这将分两部分运行它们:
tasks = []
for item in items:
tasks.append(asyncio.create_task(f(item)))
await asyncio.sleep(1) # here they start running and run for a second
res = await asyncio.gather(*tasks) # here we wait for them to complete