AsyncIO
Don’t have to use semaphores, you get access to shared memory, and it’s relatively easy to code
For applications with lots of IO, the savings can be substantial
Await coroutines
When
run_until_complete
runssay1
function, the interpreter executes it line by line, and when it seesawait
, it starts asynchronous operation which later will be finished with some internal callback to loop (such callback hidden from us, developers).But now, after the start, it immediately returns control to the event loop.
So it starts asynchronous sleep and our
loop
has control, so the loop is actually ready to start the next functionsay2
.When first
async
sleep is finished, it makes an internal callback to loop (hidden from us) and loop resumes execution ofsay1
coroutine: next operation is printingHello 1!
. After printing it returns again to the event loop.
At the same time, from the second sleep, the loop receives an event about finishing the second sleep (if 2 events will come at the same time they will not be lost, they will be just queued).
So now
Hello 2!
is printed and the second method is also returned.run_until_complete(gather(l1,l2,l3))
will block until alll1
,l2
,l3
coroutines will be done.
It can be displayed as next (assume that all red lines are at 0s
time point, and all blue at 1s
):
Last updated