I've read many examples, blog posts, questions/answers about asyncio
/ async
/ await
in Python 3.5+, many were complex, the simplest I found was probably this one. Still it uses ensure_future
, and for learning purposes about asynchronous programming in Python, I would like to see if an even more minimal example is possible (i.e. what are the minimum tools necessary to do a basic async / await example).
Question: for learning purposes about asynchronous programming in Python, is it possible to give a simple example showing how async
/ await
works, by using only these two keywords + asyncio.get_event_loop()
+ run_until_complete
+ other Python code but no other asyncio
functions?
Example: something like this:
import asyncio
async def async_foo():
print("async_foo started")
await asyncio.sleep(5)
print("async_foo done")
async def main():
asyncio.ensure_future(async_foo()) # fire and forget async_foo()
print('Do some actions 1')
await asyncio.sleep(5)
print('Do some actions 2')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
but without ensure_future
, and still demonstrates how await / async works.
This way it's possible to write code that works:
But this way it's impossible to demonstrate why you need asyncio.
By the way, why do you need
asyncio
, not just plain code? Answer is -asyncio
allows you to get performance benefit when you parallelize I/O blocking operations (like reading/writing to network). And to write useful example you need to use async implementation of those operations.Please read this answer for more detailed explanation.
Upd:
ok, here's example that uses
asyncio.sleep
to imitate I/O blocking operation andasyncio.gather
that shows how you can run multiple blocking operations concurrently:Output:
Note how both
io_related
started then, after only one second, both done.To answer your questions I will provide 3 different solutions to the same problem.
case 1: just normal python
output:
case 2: async/await done wrong
output:
case 3: async/await done right (same as case 2 except the
sleep
function)output:
case 1
withcase 2
give the same5 seconds
, whereascase 3
just3 seconds
. So theasync/await done right
is faster.The reason for the difference is within the implementation of
sleep
function.sleep
function incase 1
andcase 2
are the "same". They "sleep" without allowing others to use the resources. Whereascase 3
allows access to the resources when it is asleep.In
case 2
we addedasync
to the normal function. However the event loop will run it without interruption. Why? Because we didn't tell where the loop is allowed to interrupt your function to run another task.In
case 3
we told the event loop exactly where to interrupt the function to run another task. Where exactly?More on this read here