asyncio.Semaphore limits the number of concurrent tasks.
1import asyncio23async def fetch(url, sem):4 async with sem: # Acquire semaphore5 print(f"Fetching {url}")6 await asyncio.sleep(1) # Simulate network request7 return f"Data from {url}"89async def main():10 sem = asyncio.Semaphore(3) # Max 3 concurrent11 urls = [f"url{i}" for i in range(10)]1213 tasks = [fetch(url, sem) for url in urls]14 results = await asyncio.gather(*tasks)15 print(results)1617asyncio.run(main())18# Only 3 requests run simultaneously
Methods:
acquire() — wait for a slot.release() — free a slot.locked() — check if full.Use cases: