ConcurrencyPythonverifiedVerified

Semaphore Pattern in Python

Control access to a finite pool of resources by maintaining a counter that threads atomically increment (release) and decrement (acquire), blocking when the count reaches zero.

How to Implement the Semaphore Pattern in Python

1Step 1: Implement the Semaphore using asyncio.Semaphore

import asyncio

2Step 2: Limit concurrent tasks using the semaphore

async def main() -> None:
    semaphore = asyncio.Semaphore(3)

    async def limited_task(task_id: int) -> str:
        async with semaphore:
            await asyncio.sleep(0.1)
            return f"task-{task_id}"

    results = await asyncio.gather(
        *(limited_task(i) for i in range(10))
    )
    print(results)


if __name__ == "__main__":
    asyncio.run(main())

Semaphore Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Semaphore Pattern in the Real World

Imagine a car park with exactly three spaces. A ticket machine at the entrance (the semaphore) issues a ticket only if spaces remain, lifting the barrier; arriving drivers with no ticket available must wait. When a car exits, the machine automatically increments its counter and releases the next waiting driver — the car park never exceeds capacity.