Sobes.tech
Junior — Middle

What component manages task switching in the asyncio library?

sobes.tech AI

Answer from AI

In Python's asyncio library, task switching is managed by the event loop. This central component schedules, runs, and switches between asynchronous tasks (coroutines).

The event loop monitors when tasks are ready to run (for example, when an I/O operation is complete) and switches between them, ensuring asynchronous and non-blocking execution.

Example of using the event loop:

import asyncio

async def task(name):
    print(f"Task {name} started")
    await asyncio.sleep(1)
    print(f"Task {name} completed")

async def main():
    await asyncio.gather(task('A'), task('B'))

asyncio.run(main())

Here, the event loop manages switching between task('A') and task('B'), allowing them to run concurrently without blocking.