-
Notifications
You must be signed in to change notification settings - Fork 0
AsyncIO : Asynchronous tasking in Python
christopheseyler edited this page Aug 1, 2024
·
3 revisions
Python doc : asyncio — Asynchronous I/O
YouTube : AsyncIO and the Event Loop Explained
YouTube : Python Threading Explained in 8 Minutes
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.
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.
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
import asyncio
# Here, main is a coroutine object
async def main()
print("Start of the main coroutine")
# Run the main coroutine
asyncio.run(main())
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())
Language
Libraries
Package