tags: language programming-language python concurrent parallelism asyncio loop event-loop

Event Loop

What is an Event loop?

An event loop is a loop which has a list of tasks and it attempts to progress them in a sequence in each iteration of the loop. Along with the execute of the tasks, it also executes callbacks and IO handlings.

An event loop is the driver code that manages the cooperative multitasking.

This is the core part of asyncio library to create and run asynchronuous code in python.

Event loop implementations

Event loop is an abstract class which has to be implemented explicility according the requirements. There are several event loop implentations are avaiable.

  1. asyncio.DefaultEventLoopPolicy
  2. asyncio.ProactorEventLoop
  3. uvloop a high performance event loop implementation based on libuv library which is used in node.js for its event loop.
  4. asyncio.SelectorEventLoop

Let’s use uvloop implementation.

pip install uvloop
 
import asyncio
import uvloop
 
uvloop.install()
 
loop = asyncio.new_event_loop()
 
#<uvloop.Loop running=False closed=False debug=False>

Event loop APIs

call_soon

This is the method of event loop to schedule a callback. For instance,

def greet():
    print("greetings")
 
loop = asyncio.new_event_loop()
 
loop.call_soon(greet)
 
loop.run_forever()

It should print greetings.

There may times when we required to schedule a coroutine. Howeer, call_soon only takes function, not a coroutine. We can do by using asyncio.ensure_future which a method that creates a schedules a future wrapping the coroutine.

 
async def greet():
    await asyncio.sleep(2)
    print("greetings")
 
loop.call_soon(asyncio.ensure_future, greet())
 
loop.run_forever()

So, asyncio.ensure_future is scheduled as callbacks that takes greet() coroutine as an argument.

References

  1. # Asyncio (superseded by async)
  2. Async IO Event Loop