The asyncio module in Python
The asyncio module in Python provides support for writing concurrent, single-threaded programs using co-routines. It is available only in Python 3.
A co-routine using the asyncio module is one that uses either of the following approaches:
Using the
async defstatement for defining functionsBeing decorated using the
@asyncio.coroutineexpression
Generator-based co-routines use the second technique, and they yield from expressions.
Co-routines created using the first technique typically use the await <future> expression to wait for the future to be completed.
Co-routines are scheduled for execution using an event loop, which connects the objects and schedules them as tasks. Different types of event loop are provided for different operating systems.
The following code rewrites our earlier example of a simple cooperative multitasking scheduler to use the asyncio module:
# asyncio_tasks.py
import asyncio
def number_generator(m, n):
""" A number generator co-routine...