Core Components of Asyncio

Event Loop

The event loop is the central component of Asyncio, responsible for managing and scheduling the execution of asynchronous tasks. It continuously checks for and processes pending tasks and I/O operations, ensuring that each task progresses without blocking the execution of others. The event loop is created and managed using the asyncio.get_event_loop() function, and it can run until all tasks are completed or manually stopped.

import asyncio

async def main():
    print("Hello, Asyncio!")
    await asyncio.sleep(1)
    print("Goodbye, Asyncio!")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Coroutines

Coroutines are the building blocks of Asyncio. They are special functions defined with the async def keyword, and they can be paused and resumed during execution using the await keyword. Coroutines allow for non-blocking execution, enabling other tasks to run concurrently while waiting for an I/O operation to complete.

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(say_hello())

Tasks

Tasks are units of work created from coroutines and managed by the event loop. They allow multiple coroutines to run concurrently. Tasks can be created using the asyncio.create_task() function, and they can be awaited to get the result of the coroutine once it completes.

import asyncio

async def task_example():
    print("Task started")
    await asyncio.sleep(1)
    print("Task completed")

async def main():
    task = asyncio.create_task(task_example())
    await task

asyncio.run(main())