Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Print async

  • asyncio

  • async

  • await

  • gather

  • This is almost the same example but we wait in parallel.

  • The order of the output is now different.

  • It also finishes 1 sec faster. It finishes when the longest wait ends.

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)

Second
First
Elapsed: 2.002833483973518