Repaso
Español
PythonAdvancedPY-44

Explain how asyncio works and when you would choose it over threads or processes.

Answer

  • One thread, one event loop. Coroutines (async def) give control back at each await, so the loop can run other tasks while one waits on I/O.
  • Cooperative: any blocking call (CPU work, time.sleep, a sync DB driver) freezes everything.
  • Tools: asyncio.gather, TaskGroup, create_task, Semaphore to limit concurrency, wait_for for timeouts.
  • Choose asyncio for many simultaneous I/O operations (thousands of sockets, API fan-out, websockets).
  • Threads: simpler for a few blocking calls with sync libraries.
  • Processes: CPU-bound work.
  • Run blocking code from async with asyncio.to_thread / run_in_executor.

Key terms

Practice this question in Repaso