2

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

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Don't we need to perform loop.close()?
We do, added :) @Mihika
3

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())
answered Jan 22, 2019 at 12:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.