Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.Semaphore

Restricts concurrent access using a counter of available permits.

Version: Python 3.14; repository image, production runtime not attested

Syntax

asyncio.Semaphore(value=1)

Restricts concurrent access using a counter of available permits.

Exhausting permits blocks future acquisition. Exiting a managed section releases a permit even if the body fails.

Limit simultaneous resource users with a permit counter. acquire takes one or suspends at zero, and release gives one back. A negative initial value raises ValueError. Unlike BoundedSemaphore, an extra release may increase capacity beyond its initial value. Starting from two, locked() reports False, True, False through the nested scopes. locked() indicates that an immediate acquisition would block. BoundedSemaphore raises ValueError if release would exceed the initial capacity.

import asyncio
async def main():
    s = asyncio.Semaphore(1)
    assert await s.acquire() and s.locked()
    s.release()
    s.release()
    assert await s.acquire() and not s.locked()
    assert await s.acquire() and s.locked()
    try:
        asyncio.Semaphore(-1)
    except ValueError:
        pass
    else:
        raise AssertionError
asyncio.run(main())
import asyncio
async def main():
    b = asyncio.BoundedSemaphore(1)
    assert not b.locked()
    await b.acquire()
    assert b.locked()
    b.release()
    try:
        b.release()
    except ValueError:
        pass
    else:
        raise AssertionError
asyncio.run(main())

Examples

import asyncio

async def main():
    sem = asyncio.Semaphore(2)
    async with sem:
        print(sem.locked())
        async with sem:
            print(sem.locked())
        print(sem.locked())

asyncio.run(main())

Result

False
True
False

Limit simultaneous resource users with a permit counter. acquire takes one or suspends at zero, and release gives one back. A negative initial value raises ValueError. Unlike BoundedSemaphore, an extra release may increase capacity beyond its initial value. Starting from two, locked() reports False, True, False through the nested scopes. locked() indicates that an immediate acquisition would block. BoundedSemaphore raises ValueError if release would exceed the initial capacity.

Sources