Junior — Middle
How does task switching occur in coroutines when using asyncio?
sobes.tech AI
Answer from AI
In asyncio, task (coroutine) switching occurs at the point of a wait (await), where the coroutine is paused, allowing the event loop to switch to executing another coroutine. Thus, task switching is cooperative: a coroutine voluntarily yields control, waiting for an asynchronous operation to complete, such as I/O. This allows efficient use of waiting time without blocking the thread.
Example:
import asyncio
async def task(name):
print(f"{name} started")
await asyncio.sleep(1) # switch point
print(f"{name} finished")
async def main():
await asyncio.gather(task("A"), task("B"))
asyncio.run(main())