Print async
- This is almost the same example as the previous one using sync, but we wait asynchronously.
- The order of the output is now different.
- It also finishes 1 sec faster. It finishes when the longest wait ends.
What did we don?
- We added
asyncin-front of the function definitions to make them co-routines. - We replaced the
time.sleepbyasyncio.sleepthat can handle async sleep. - We called this new
sleepfunction with theawaitkeyword. That tells the even-loop that other tasks can run till this thing we are awaiting-for finishes. - We called the
sayfunction inside anawait-ed call toasyncio.gather. - We started the event loop with
asyncio.run.
Code
import time
import asyncio
async def say(text, sec):
await asyncio.sleep(sec)
print(text)
async def main():
print('start main')
start = time.monotonic()
await asyncio.gather(
say("First", 2),
say("Second", 1),
)
end = time.monotonic()
print(f"Elapsed: {end-start}")
main_co = main()
print(main_co)
asyncio.run(main_co)
Output
<coroutine object main at 0x78265ad9a4d0>
start main
Second
First
Elapsed: 2.0022734529920854
The first print shows that what the main function returns is a object of type coroutine.
The "Second" print appears before the "First", because the former only had to wait 1 second why the latter waited 2 seconds.
- asyncio
- async
- await
- gather