Dev Helpers
← Back

Limit concurrency with a semaphore

Limit concurrency with a semaphore. A self-contained example using the Python standard library.

Open this example in the interactive library

Source code

import asyncio
async def main():
    gate = asyncio.Semaphore(2)
    async def work(n):
        async with gate:
            await asyncio.sleep(0)
            return n
    return await asyncio.gather(*(work(n) for n in range(4)))
print(asyncio.run(main()))

Sample output

[0, 1, 2, 3]