Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.Semaphore

synchronization

A counter of permits: it lets at most N tasks into the async with block at once. The typical use is capping the number of concurrent requests.

Syntax

sem = asyncio.Semaphore(value=1)
async with sem: ...

A semaphore limits concurrency, not rate: all tasks are still created up front and wait their turn inside, so thousands of coroutines in gather() still take memory. An extra release() without acquire() silently raises the counter above its start value — a logic bug then lets more tasks through than intended; asyncio.BoundedSemaphore exists to catch that.

Examples

import asyncio
active = 0
peak = 0
async def job(sem):
    global active, peak
    async with sem:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.01)
        active -= 1
async def main():
    sem = asyncio.Semaphore(2)
    await asyncio.gather(*(job(sem) for _ in range(6)))
    print(peak)  # → 2 — больше двух одновременно не было
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy