0

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?

SercioSoydanov
  • 980
  • 10
  • 29
  • Not a duplicate, but you may find useful: https://stackoverflow.com/questions/37278647/fire-and-forget-python-async-await – tevemadar Apr 06 '21 at 11:20

1 Answers1

1

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

apr_1985
  • 1,764
  • 2
  • 14
  • 27
  • Extremely helpful, but I still don't understand what's the poing on executing something like I've illustrated in the first code snippet. If await blocks the code execution of the caller line, why bother declaring a function as an asynchronous function and calling it with await? Isn't that the same thing with executing a synchronous function call? – SercioSoydanov Apr 06 '21 at 11:33
  • So without the `async` then a function cannot be called asynchronously at all. `await` will tell Python to execute the function asynchronously, but Python can only do that as part of a `gather` or an event loop `asyncio.get_event_loop()` otherwise it just runs the one command async which is the same as sequential running. Take a look at this https://stackabuse.com/python-async-await-tutorial/ I found it helpful when trying out async – apr_1985 Apr 06 '21 at 12:56