I have just started learning asyncio in Python, and wrote the following code:
import asyncio
loop = asyncio.get_event_loop()
async def hello():
print("Hello")
await asyncio.sleep(3)
print("World")
if __name__ == '__main__':
for i in range(3):
loop.run_until_complete(hello())
loop.close()
This gives me the following output:
Hello
<waits for 3 seconds>
World
Hello
<waits for 3 seconds>
World
Hello
<waits for 3 seconds>
World
How can I modify the program so that the same is handled asynchronously (i.e. once the first task sleeps, the second one begins executing), essentially giving output similar to this:
Hello
Hello
Hello
World
World
World
asked Jan 22, 2019 at 12:09
Mihika
5551 gold badge5 silver badges22 bronze badges
2 Answers 2
You can asyncio.gather them.
import asyncio
async def hello():
print("Hello")
await asyncio.sleep(3)
print("World")
async def lots_of_hello():
cur_list = []
for _ in range(3):
cur_list.append(hello())
await asyncio.gather(*cur_list)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(lots_of_hello())
loop.close()
answered Jan 22, 2019 at 12:23
Yuval Pruss
10.2k16 gold badges48 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mihika
Don't we need to perform loop.close()?
Yuval Pruss
We do, added :) @Mihika
I'm also new to asyncio, but I got curious reading your question and tried to explore it a little bit. This is what I got, something different than the previous answer, with an extra candy of variable sleep time ;) :
import asyncio
async def hello(timeToSleep):
print("Hello")
await asyncio.sleep(timeToSleep)
print("World")
async def main():
tasks = []
for i in range(3):
tasks.append(asyncio.create_task(hello(i)))
for task in tasks:
await task
if __name__ == '__main__':
asyncio.run(main())
Comments
lang-py