SercioSoydanov
SercioSoydanov

Reputation: 1400

Fundamental logic of async / await functions

Consider these two Python snippets:

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

and this one:

import time


def say_after(delay, what):
    time.sleep(delay)
    print(what)


def main():
    print(f"started at {time.strftime('%X')}")

    say_after(1, "hello")
    say_after(2, "world")

    print(f"finished at {time.strftime('%X')}")

main()

they produce exactly the same output, the flow of main() pauses after each function call.

So what's the difference between a synchronous flow and an asynchronous one in this example? And what's the point on using async/sync if the main flow is being paused / blocked?

Upvotes: 0

Views: 114

Answers (1)

apr_1985
apr_1985

Reputation: 1962

Doing multiple awaits will still only add a single await to the execution loop at a time. You can use await asyncio.gather to add multiple awaits

async def main():
    print(f"started at {time.strftime('%X')}")
    await asyncio.gather(say_after(5, 'banana'), say_after(1, 'hello'), say_after(2, 'world'))
    print(f"finished at {time.strftime('%X')}")

would yield

started at 12:12:39
hello
world
banana
finished at 12:12:44

I am not an async expert but I have used this in the past to run off multiple lookups to systems etc

Upvotes: 1

Related Questions