Python Glossary Русский

all Python 3multiprocessingterm

multiprocessing.Semaphore

synchronization

A semaphore shared between processes: a permit counter that limits how many processes do one thing at the same time.

Syntax

sem = ctx.Semaphore(value=1); sem.acquire(block=True, timeout=None); sem.release()

A plain Semaphore does not check for extra release() calls: the counter rises above its initial value and the limit quietly weakens; BoundedSemaphore guards against that mistake. The acquire() argument is named block, not blocking as in threading: acquire(blocking=False) raises TypeError. get_value() raises NotImplementedError on macOS. Pass the primitive to the child as a Process argument at creation; it cannot go through a Queue or Pool arguments — RuntimeError "should only be shared between processes through inheritance".

Examples

import multiprocessing as mp
if __name__ == '__main__':
    sem = mp.get_context('spawn').Semaphore(1)
    print(sem.acquire(timeout=0.1), sem.acquire(timeout=0.1))  # → True False
    sem.release()
    sem.release()  # лишний release ошибки не даёт
    print([sem.acquire(False) for _ in range(3)])  # → [True, True, False]
    try:
        sem.acquire(blocking=False)
    except TypeError:
        print('use block=, not blocking=')  # → use block=, not blocking=

See also

Open in the full glossarydocs.python.orgReport an inaccuracy