Asyncio

11 Jan 2020

asyncio

1. Introduction to coroutine

Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed.This means that unlike Threads which can be preempted from OS, coroutines are not prempted from outside but give control themselves. This avoids any requirment of synchronisation primitives such as lock or critical section

2. The big picture


Consider an event loop with 2 queue, ready and waiting. We create a new task/coroutine to perform an IO operation or configure remote device and put it in ready queue. Initially execution control is with event loop which it passes to the new task in ready queue. Task starts execution. Whenever task need to wait from results, it can move to waiting queue and give control back to event loop. Event loop then gives the control to next task in ready queue. Meanwhile when task get the result, it is moved from waiting to ready queue.

3. Async and await syntax

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())

asyncio.run function runs the passed coroutine, taking care of managing the asyncio event loop.