Python Glossary Русский

Python 3.3+multiprocessingterm

multiprocessing.Barrier

synchronization

A barrier shared between processes: a fixed number of parties wait for each other in wait() and then move on together. Added in Python 3.3.

Syntax

b = ctx.Barrier(parties, action=None, timeout=None); b.wait(timeout=None)

It is the process version of threading.Barrier, and it raises the same threading.BrokenBarrierError, not anything from multiprocessing. If a party never arrives (it crashed or fewer were started), the rest wait forever, so set a timeout: it breaks the whole barrier, and every later wait() also gets BrokenBarrierError until reset(). The main process can be a party too; count it in parties. 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
def party(b):
    b.wait(timeout=10)
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    b = ctx.Barrier(2)  # участники: ребёнок и главный процесс
    p = ctx.Process(target=party, args=(b,))
    p.start()
    b.wait(timeout=10)
    print('both passed')  # → both passed
    p.join()
import multiprocessing as mp
import threading
if __name__ == '__main__':
    b = mp.get_context('spawn').Barrier(2)
    try:
        b.wait(timeout=0.1)  # второго участника нет
    except threading.BrokenBarrierError:
        print('broken:', b.broken)  # → broken: True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy