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 gather
CodePudding user response:
First, note that you must await asyncio.gather() for them to run at all.
Once that is fixed, the functions will run only once. create_task() submits them to the event loop. After that, they will run during the next await. asyncio.gather() simply ensures that the calling coroutine awaits their completion. 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
