Overview:
-
The asyncio module of Python enables executing coroutines through Tasks and Futures.
-
A coroutine is expected to be suspended several times as it yields the CPU, while waiting for an awaitable object to do some processing.
-
To execute a single coroutine or multiple coroutines several times, a programmer can not code all of the start/resume sequence(suspend is taken care by the coroutine itself) line by line. Instead, a loop can execute them. asyncio offers this loop, which is called an event loop that executes the coroutines through Task objects.
-
The computations done by a coroutine are abstracted as a Task in the asyncio.
-
The create_task() function of the asyncio module creates and returns a Task from a coroutine. These Task instances are executed by the event loop provided by the Python's asyncio module.
-
It is required to have an event loop created before calling create_task(). The Task is created and executed on this event loop.
-
The asyncio module allows custom event loops to be used for the task execution.
Example:
# Example Python program that executes # A list of messages # A list of new messages # Source file # Target file # Coroutine that reads messages from # Coroutine that transforms messages # Coroutine that reads the transformed #print("W:%s"%nmsg) # A coroutine that creates tasks and waits on them # Create a new event loop and make it to run the tasks # Now run the tasks(in the event loop) |
Output:
a1 b1 c1 d1 |