Search GimmeJob

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

Run many async operations concurrently while limiting the number that may be active at once.

Answer

Use an `asyncio.Semaphore` around the resource-intensive portion of each coroutine, then schedule all work and await it with `asyncio.gather` or a TaskGroup. The semaphore gives concurrency without allowing an unbounded burst against an API or database. Keep the `async with semaphore` scope as small as possible so unrelated local work does not consume a permit.

Strong answer includes

  • uses asyncio.Semaphore
  • schedules multiple coroutines concurrently
  • limits only the resource-sensitive section

Practical example

Bound concurrent async work with a semaphore
Python
editable · browser sandbox
Result
Run the code to see the result.

All ten coroutines are scheduled, but only three can hold the semaphore and execute the protected simulated I/O concurrently.

Expected result: 10.

#asyncio#semaphore#concurrency

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