Python 3.2+threadingterm
threading.Barrier
synchronization
A barrier: a fixed number of threads wait for each other in wait() and then all move on together — a shared starting line before the next phase of work.
Syntax
barrier = threading.Barrier(parties, action=None, timeout=None)
index = barrier.wait(timeout=None)
The barrier opens only when exactly parties threads have entered wait(): if one crashed or fewer were started, the rest hang forever, so pass a timeout. A timeout breaks the whole barrier: every waiting and every later wait() raises BrokenBarrierError until you call reset(). wait() hands each thread a distinct number from 0 to parties-1, so exactly one thread can do the shared step (the action parameter does the same). Unlike Event, a barrier is reusable: after a pass it is ready for the next round by itself.
Examples
import threading
barrier = threading.Barrier(3)
lock = threading.Lock()
log, numbers = [], []
def worker(name):
with lock:
log.append('ready')
n = barrier.wait()
with lock:
log.append('go')
numbers.append(n)
threads = [threading.Thread(target=worker, args=(c,)) for c in 'abc']
for t in threads:
t.start()
for t in threads:
t.join()
print(log[:3], sorted(numbers)) # → ['ready', 'ready', 'ready'] [0, 1, 2]
import threading
barrier = threading.Barrier(2, timeout=0.1)
try:
barrier.wait() # второй участник так и не пришёл
except threading.BrokenBarrierError:
print('broken:', barrier.broken) # → broken: True
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy