Sobes.tech
Middle+

How does asyncio event loop and asyncio.gather work?

sobes.tech AI

Answer from AI

In Python, asyncio is a library for writing asynchronous code using an event loop.

asyncio event loop is a loop that manages the execution of asynchronous tasks, waits for their completion, and switches between them without blocking the main thread.

asyncio.gather is a function that allows running multiple coroutines (asynchronous functions) in parallel and waiting for their completion. It takes several awaitable objects and returns the result as a list.

Example:

import asyncio

async def say_after(delay, message):
    await asyncio.sleep(delay)
    return message

async def main():
    results = await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world')
    )
    print(results)  # ['hello', 'world']

asyncio.run(main())

Here, the event loop runs both tasks simultaneously, without blocking execution, and collects their results.