I was going through the Python documentation for asyncio
and I'm wondering why most examples use loop.run_until_complete()
as opposed to Asyncio.ensure_future()
.
For example: https://docs.python.org/dev/library/asyncio-task.html
It seems ensure_future
would be a much better way to demonstrate the advantages of non-blocking functions. run_until_complete
on the other hand, blocks the loop like synchronous functions do.
This makes me feel like I should be using run_until_complete
instead of a combination of ensure_future
with loop.run_forever()
to run multiple co-routines concurrently.
run_until_complete
is used to run a future until it's finished. It will block the execution of code following it. It does, however, cause the event loop to run. Any futures that have been scheduled will run until the future passed torun_until_complete
is done.Given this example:
do_io
will run. After it's complete,do_other_things
will run. Your output will be:If you schedule
do_other_things
with the event loop before runningdo_io
, control will switch fromdo_io
todo_other_things
when the former awaits.This will get you the output of:
This is because
do_other_things
was scheduled beforedo_io
. There are a lot of different ways to get the same output, but which one makes sense really depends on what your application actually does. So I'll leave that as an exercise to the reader.