Throttle parallel access to a finite resource.
Section: Synchronization Primitives
Limit concurrency with a Semaphore
python
python
import asyncio
sem = asyncio.Semaphore(3)
async def fetch(i):
async with sem:
print("start", i)
await asyncio.sleep(0.2)
print("done", i)
async def main():
await asyncio.gather(*(fetch(i) for i in range(8)))
asyncio.run(main())Explanation
Useful for rate-limited APIs, database pools, and bounded parallelism.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Synchronization Primitives
Protect shared state with a Lock
Prevent overlapping access to a critical section.
Signal readiness with an Event
Wake waiting tasks once a condition becomes true.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.