Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Concurrency & parallelismSeniorVery commonTheory

How does the asyncio event loop achieve concurrency with a single thread, and what makes a function a coroutine?

Answer

A function defined with `async def` is a coroutine function; calling it returns a coroutine object that does nothing until it is awaited or scheduled as a task. The event loop runs one coroutine at a time on a single thread, and whenever that coroutine hits an `await` on something that would block (like network I/O), it voluntarily yields control back to the loop, which then runs another ready coroutine in the meantime. This is cooperative multitasking: concurrency comes from many coroutines taking turns at `await` points, not from parallel execution, so a coroutine that never awaits (pure CPU work) blocks the entire event loop for everyone.

Strong answer includes

  • async def creates a coroutine function, calling it just returns an object
  • the loop runs one coroutine at a time, switching at await points
  • cooperative, not parallel — a non-awaiting coroutine blocks everything

Practical example

Concurrent I/O with asyncio.gather
Python
editable · browser sandbox
Result
Run the code to see the result.

Each coroutine yields control at await, letting the event loop run another ready coroutine. gather preserves input order in its returned results even if b finishes first.

Expected result: ['a', 'b'] after roughly 0.2 seconds rather than 0.3 seconds of serial waiting.

#asyncio#coroutines#event-loop

Sources

asyncio — Asynchronous I/OPython Software Foundation · Event loop, coroutines, tasks and structured concurrency primitivesPEP 492 — Coroutines with async and await syntaxPython Software Foundation · The origin of async/await syntax and native coroutine objects