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
Python
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.