Skip to content

AsyncIO : Asynchronous tasking in Python

christopheseyler edited this page Aug 1, 2024 · 3 revisions

AsyncIO : Asynchronous tasking in Python

Reference

Python doc : asyncio — Asynchronous I/O

YouTube : AsyncIO and the Event Loop Explained

YouTube : Python Threading Explained in 8 Minutes

Introduction

AsyncIO provides a way to implement concurency operations within Python. The AsyncIO mechanism relies on an Event-Loop that gathers operations to execute and dispatch their execution within a single thread.

Event Loop

IN the older version of Python, the access to an event loop has to be explicit : creation, interaction and close. On the modern Python, they introducted async keyword to specify that the function (or method) will be executed in the context of an event loop.

Coroutine

The coroutines are operations that will be executed in the background, sequenced by the event loop. A coroutine can be

  • executed by await : blocking call that waits the completion of the coroutine
  • executed in the scope of a task

Usage

Creation and call of a coroutine

import asyncio

# Here, main is a coroutine object
async def main() 
	print("Start of the main coroutine")
	
# Run the main coroutine
asyncio.run(main())

How to wait on a coroutine

import asyncio

async def fetch_data(delay, id):
	print("Fetching data... id:", id)
	await asyncio.sleep(delay) # simulate an I/O operation
	print("Data Fetched , id:", id)
	return {"data":"some data", "id":id} # Return some data


async def main():
	task1 = fetch_data(2, 1)
	task2 = fetch_data(3, 2)
	
	result1 = await task1
	print(f"Received result: {result1}")
	
	result2 = await task2
	print(f"Received result: {result2}")
		
# Run the main coroutine
asyncio.run(main())