How asyncio works? and event loop vs exceptions

Terry Reedy tjreedy at udel.edu
Sat Jul 23 05:56:25 EDT 2016


On 7/22/2016 8:27 PM, Marco S. via Python-list wrote:
> I'm developing a web app based on aiohttp, and I find the event loop
> concept very interesting. I never programmed with it before, but I
> know that node.js and GUIs are based on it.
>
> What I can't understand is how asyncio make it possible to run
> multiple tasks concurrently, since it's single threaded (if you don't
> use loop.run_in_executor()). I just tried to imagine that it should
> act as a cpu scheduler. Is this true?

The code for BaseEventLoop is in asyncio.base_events.py.  In particular, 
see def run_forever.  Very simplified,

def run_forever():
     while True:
         handle_ready_io_events()
         call_ready_scheduled_functions()

 > If so, how and when asyncio decide to switch to another task?

It does not decide.  Asyncio does *cooperative* multi-tasking.  This 
depends on handlers running for a short time and quitting, even if there 
is more work to do.  The OS does *pre-emptive* multi-tasking; it 
switches processes that are still running.

It is possible to add other events into the mix.  Adding these lines

def tk_update():
     root.update()
     loop.call_later(.01, tk_update)
tk_update()

to an asyncio program before loop.run_forever and the loop will drive a 
tkinter gui.  A day ago, I experimentally patched IDLE to run off of an 
asyncio loop instead of the tk loop.  Everything I tried worked.  See 
https://bugs.python.org/issue27546.

> Furthermore I have a question about exceptions in asyncio.

I am too ignorant about this to even ask.

-- 
Terry Jan Reedy




More information about the Python-list mailing list