Reputation: 629
In Python, we need an await
keyword before each coroutine object to have it called by the event loop. But when we put await
, it makes the call blocking. It follows that we end up doing the same thing as we do in the blocking fashion. What is the point of having such a use?
https://www.aeracode.org/2018/02/19/python-async-simplified/
https://stackabuse.com/python-async-await-tutorial/
Upvotes: 13
Views: 11024
Reputation: 4893
Using await
does NOT make the call synchronous. It is just syntactic sugar to make it look like "normal" sequential code. But while the result of the function call is await
ed the event loop still continues in the background.
For example the following code executes foo()
twice which will await
a sleep
. But even though it uses await
the second function invokation will execute before the first one finishes. Ie. it runs in parallel.
import asyncio
async def main():
print('started')
await asyncio.gather(
foo(),
foo(),
)
async def foo():
print('starting foo')
await asyncio.sleep(0.1)
print('foo finished.')
asyncio.run(main())
prints:
started
starting foo
starting foo
foo finished.
foo finished.
Upvotes: 12
Reputation: 42492
await
makes the call locally blocking, but the "wait" is transmitted through the async function (which is itself awaited), such that when it reaches the reactor the entire task can be moved to a waitlist and an other can be run instead.
Furthermore you do not need an await
, you could also spawn
the coroutine (to a separate task, which you may or may not wait on), or use one of the "future combinators" (asyncio.gather
, asyncio.wait
, ...) to run it concurrently with others.
Upvotes: 4