Python Barrier
last modified November 29, 2026 Python 3.15
In this article we show how to synchronize Python threads with
threading.Barrier.
A barrier is a synchronization point for a fixed number of
threads. Each thread calls wait when it reaches the point and
blocks there. When the last thread arrives, all of them are released at the
same time. The number of threads the barrier waits for is called the number
of parties.
Barriers are useful when work is done in phases and no thread may start the
next phase before every thread has finished the current one. A
Barrier is reusable: after it releases the threads, it is ready
for the next round.
First barrier
In the first program three threads arrive at the barrier at different times. None of them passes before the last one arrives.
import threading
import time
barrier = threading.Barrier(3)
def worker(name, delay):
time.sleep(delay)
print(f'{name} arrived at the barrier')
barrier.wait()
print(f'{name} passed the barrier')
threads = [threading.Thread(target=worker, args=(f'worker-{i}', i * 0.2))
for i in range(1, 4)]
for t in threads:
t.start()
for t in threads:
t.join()
Each worker sleeps for a different time to simulate work of a different length. Then it waits at the barrier.
barrier = threading.Barrier(3)
The barrier is created for three parties. The third call to
wait releases all three threads.
barrier.wait()
The wait method blocks the calling thread until all parties have
called it. The threads arrive in the order of their delays, but after the
barrier they run concurrently, so the order of the last three lines can
differ between runs.
$ python first_barrier.py worker-1 arrived at the barrier worker-2 arrived at the barrier worker-3 arrived at the barrier worker-3 passed the barrier worker-1 passed the barrier worker-2 passed the barrier
Measuring the wait
A barrier makes the fast threads wait for the slow ones. We can see it by recording the time when each thread arrives and when it leaves.
import threading
import time
barrier = threading.Barrier(3)
start = time.perf_counter()
def elapsed():
return time.perf_counter() - start
def worker(name, delay):
time.sleep(delay)
arrived = elapsed()
barrier.wait()
left = elapsed()
print(f'{name}: arrived {arrived:.1f} s, left {left:.1f} s, '
f'waited {left - arrived:.1f} s')
threads = [threading.Thread(target=worker, args=(f'worker-{i}', i * 0.3))
for i in range(1, 4)]
for t in threads:
t.start()
for t in threads:
t.join()
The workers arrive after 0.3, 0.6, and 0.9 seconds. All of them leave at 0.9 seconds, when the slowest worker arrives.
start = time.perf_counter()
def elapsed():
return time.perf_counter() - start
The elapsed helper returns the number of seconds since the
program started.
print(f'{name}: arrived {arrived:.1f} s, left {left:.1f} s, '
f'waited {left - arrived:.1f} s')
The first worker waits the longest; the last one does not wait at all. The total time of a phase is the time of its slowest thread. As before, the order of the lines can differ between runs.
$ python waiting_times.py worker-3: arrived 0.9 s, left 0.9 s, waited 0.0 s worker-2: arrived 0.6 s, left 0.9 s, waited 0.3 s worker-1: arrived 0.3 s, left 0.9 s, waited 0.6 s
The wait index
The wait method returns an integer in the range 0 to
parties - 1. Every thread gets a different number, so we can use
it to pick one thread for work that must be done only once.
import threading
import time
barrier = threading.Barrier(4)
results = {}
def worker(name, value):
time.sleep(value / 10)
results[name] = value * value
idx = barrier.wait()
if idx == 0:
total = sum(results.values())
print(f'{name} got index 0 and reports: total = {total}')
threads = [threading.Thread(target=worker, args=(f'worker-{i}', i))
for i in range(1, 5)]
for t in threads:
t.start()
for t in threads:
t.join()
Each worker computes a square and stores it in a shared dictionary. After the barrier, all results are in place, and the thread that got index 0 prints the total.
idx = barrier.wait()
if idx == 0:
total = sum(results.values())
Reading results after the barrier is safe because every worker
has finished writing before any of them is released. Exactly one thread gets
index 0, so the total is printed once. Which thread gets which index is an
implementation detail; in CPython the first thread to arrive gets 0.
$ python wait_index.py worker-1 got index 0 and reports: total = 30
Barrier action
The action parameter takes a callable. When all parties have
arrived, one of the threads calls it before any thread is released. This is a
simpler way to do the work of the previous example.
import threading
import time
parts = []
def merge():
name = threading.current_thread().name
print(f'{name} runs the action: {" ".join(sorted(parts))}')
barrier = threading.Barrier(3, action=merge)
def worker(word, delay):
time.sleep(delay)
parts.append(word)
print(f'{threading.current_thread().name} added {word!r}')
barrier.wait()
words = ['apple', 'cherry', 'banana']
threads = [threading.Thread(target=worker, args=(w, i * 0.1), name=f'T{i}')
for i, w in enumerate(words, 1)]
for t in threads:
t.start()
for t in threads:
t.join()
Three threads add a word to a shared list. The action sorts the words and prints them.
barrier = threading.Barrier(3, action=merge)
The merge function is called once per round, after the third
thread reaches the barrier.
def merge():
name = threading.current_thread().name
print(f'{name} runs the action: {" ".join(sorted(parts))}')
The action runs in one of the waiting threads; in CPython it is the last
thread to arrive. If the action raises an exception, the barrier is put into
the broken state and every waiting thread gets a
BrokenBarrierError.
$ python barrier_action.py T1 added 'apple' T2 added 'cherry' T3 added 'banana' T3 runs the action: apple banana cherry
Work in phases
Because a barrier resets itself after releasing the threads, the same object can separate several phases of work.
import threading
import time
def end_of_phase():
print('--- phase done ---')
barrier = threading.Barrier(3, action=end_of_phase)
phases = ['download', 'parse', 'save']
def worker(name, speed):
for phase in phases:
time.sleep(speed)
print(f'{name} finished {phase}')
barrier.wait()
workers = [('fast', 0.1), ('medium', 0.2), ('slow', 0.3)]
threads = [threading.Thread(target=worker, args=w) for w in workers]
for t in threads:
t.start()
for t in threads:
t.join()
print('all phases complete')
Three workers of different speed go through three phases. No worker starts a phase before all of them have finished the previous one.
for phase in phases:
time.sleep(speed)
print(f'{name} finished {phase}')
barrier.wait()
The wait call at the end of the loop body is the boundary
between phases. Without it, the fast worker would finish all three phases
before the slow one finished the first.
def end_of_phase():
print('--- phase done ---')
The action runs once at the end of every phase, between the last arrival and the release.
$ python phases.py fast finished download medium finished download slow finished download --- phase done --- fast finished parse medium finished parse slow finished parse --- phase done --- fast finished save medium finished save slow finished save --- phase done --- all phases complete
Barrier state
A barrier has three read-only attributes: parties is the number
of threads required, n_waiting is the number of threads
currently waiting, and broken tells whether the barrier is in the
broken state.
import threading
import time
barrier = threading.Barrier(3)
def worker(delay):
time.sleep(delay)
barrier.wait()
threads = [threading.Thread(target=worker, args=(d,)) for d in (0.1, 0.3, 0.7)]
for t in threads:
t.start()
print(f'parties: {barrier.parties}')
for _ in range(5):
print(f'waiting: {barrier.n_waiting}, broken: {barrier.broken}')
time.sleep(0.2)
for t in threads:
t.join()
The main thread checks the barrier every 0.2 seconds while three workers arrive after 0.1, 0.3, and 0.7 seconds.
for _ in range(5):
print(f'waiting: {barrier.n_waiting}, broken: {barrier.broken}')
time.sleep(0.2)
The number of waiting threads grows to two and drops back to zero after the third worker arrives and the barrier releases everyone.
$ python barrier_state.py parties: 3 waiting: 0, broken: False waiting: 1, broken: False waiting: 2, broken: False waiting: 2, broken: False waiting: 0, broken: False
Timeouts
A thread that never reaches the barrier would block the others forever. A
timeout prevents this. When it expires, the barrier is put into the broken
state, and all waiting threads, as well as threads that call
wait later, get a BrokenBarrierError.
import threading
import time
barrier = threading.Barrier(3, timeout=0.5)
def worker(name, delay):
time.sleep(delay)
try:
barrier.wait()
print(f'{name} passed the barrier')
except threading.BrokenBarrierError:
print(f'{name}: the barrier is broken')
workers = [('worker-1', 0.1), ('worker-2', 0.2), ('worker-3', 2.0)]
threads = [threading.Thread(target=worker, args=w) for w in workers]
for t in threads:
t.start()
for t in threads:
t.join()
print(f'broken: {barrier.broken}')
The third worker arrives after two seconds, but the barrier gives up after 0.5 seconds of waiting.
barrier = threading.Barrier(3, timeout=0.5)
The timeout argument sets the default timeout for all
wait calls. A single call can override it with
barrier.wait(timeout).
try:
barrier.wait()
print(f'{name} passed the barrier')
except threading.BrokenBarrierError:
print(f'{name}: the barrier is broken')
The first two workers get the exception when the timeout expires. The third
worker gets it immediately when it finally calls wait, because
the barrier is already broken.
$ python barrier_timeout.py worker-1: the barrier is broken worker-2: the barrier is broken worker-3: the barrier is broken broken: True
Aborting a barrier
If a thread fails, its partners should not wait for it. The
abort method breaks the barrier at once, so the waiting threads
get a BrokenBarrierError without waiting for a timeout.
import threading
import time
barrier = threading.Barrier(3)
def load(name, path):
try:
if not path.endswith('.csv'):
raise ValueError(f'unsupported file {path}')
time.sleep(0.2)
print(f'{name} loaded {path}')
except ValueError as e:
print(f'{name} failed: {e}')
barrier.abort()
return
try:
barrier.wait()
print(f'{name} continues')
except threading.BrokenBarrierError:
print(f'{name} stops, another worker failed')
files = ['users.csv', 'orders.xml', 'items.csv']
threads = [threading.Thread(target=load, args=(f'worker-{i}', f))
for i, f in enumerate(files, 1)]
for t in threads:
t.start()
for t in threads:
t.join()
Three workers load files. The second one gets a file it cannot handle and aborts the barrier.
except ValueError as e:
print(f'{name} failed: {e}')
barrier.abort()
return
The failing worker breaks the barrier and ends. The other two workers finish loading their files, find the barrier broken, and stop instead of continuing with incomplete data.
$ python barrier_abort.py worker-2 failed: unsupported file orders.xml worker-1 loaded users.csv worker-1 stops, another worker failed worker-3 loaded items.csv worker-3 stops, another worker failed
Resetting a barrier
A broken barrier stays broken. The reset method returns it to
the default, empty state so that it can be used again. Threads waiting at the
barrier during the reset get a BrokenBarrierError.
import threading
import time
barrier = threading.Barrier(2, timeout=0.3)
def worker(name, delay):
time.sleep(delay)
try:
barrier.wait()
print(f' {name} passed')
except threading.BrokenBarrierError:
print(f' {name} found the barrier broken')
def run_round(label, delay):
print(label)
threads = [threading.Thread(target=worker, args=('A', 0)),
threading.Thread(target=worker, args=('B', delay))]
for t in threads:
t.start()
for t in threads:
t.join()
run_round('first round', 1.0)
print(f'broken: {barrier.broken}')
barrier.reset()
print(f'after reset, broken: {barrier.broken}')
run_round('second round', 0.1)
In the first round, thread B comes too late and the barrier breaks. After the reset, the second round succeeds.
barrier.reset()
print(f'after reset, broken: {barrier.broken}')
The reset call clears the broken state. It should be called when
no thread is waiting at the barrier; here the threads of the first round have
already been joined.
$ python barrier_reset.py first round A found the barrier broken B found the barrier broken broken: True after reset, broken: False second round B passed A passed
Barriers and thread pools
A barrier needs as many threads as it has parties, all running at the same
time. With a thread pool that has fewer workers, the tasks that would reach
the barrier last never start, because the pool threads are blocked in
wait.
import threading
from concurrent.futures import ThreadPoolExecutor
barrier = threading.Barrier(3, timeout=1)
def task(n):
try:
barrier.wait()
return f'task {n} passed'
except threading.BrokenBarrierError:
return f'task {n} broke the barrier'
for workers in (2, 3):
barrier.reset()
with ThreadPoolExecutor(max_workers=workers) as pool:
results = list(pool.map(task, range(1, 4)))
print(f'max_workers={workers}: {results}')
We run three tasks that wait at a barrier for three parties, first in a pool of two threads and then in a pool of three.
barrier = threading.Barrier(3, timeout=1)
The timeout turns a deadlock into an error. With two workers, tasks 1 and 2 block the whole pool; after one second the barrier breaks, and task 3 then finds it broken.
for workers in (2, 3):
barrier.reset()
The barrier is reset before each run, so the broken state from the first run does not affect the second one.
$ python pool_barrier.py max_workers=2: ['task 1 broke the barrier', 'task 2 broke the barrier', 'task 3 broke the barrier'] max_workers=3: ['task 1 passed', 'task 2 passed', 'task 3 passed']
Parallel simulation
Barriers are common in simulations that compute a new state from the old one in steps. Each thread computes a part of the new state, and nobody may read the next state before every part is ready.
import threading
N_WORKERS = 3
STEPS = 5
temps = [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100.0]
new_temps = temps[:]
def show():
print(' '.join(f'{t:5.1f}' for t in temps))
def commit():
temps[:] = new_temps
show()
barrier = threading.Barrier(N_WORKERS, action=commit)
def worker(first, last):
for _ in range(STEPS):
for i in range(first, last):
new_temps[i] = (temps[i - 1] + temps[i] + temps[i + 1]) / 3
barrier.wait()
inner = len(temps) - 2
chunk = inner // N_WORKERS
threads = []
for k in range(N_WORKERS):
first = 1 + k * chunk
last = first + chunk if k < N_WORKERS - 1 else len(temps) - 1
threads.append(threading.Thread(target=worker, args=(first, last)))
show()
for t in threads:
t.start()
for t in threads:
t.join()
The program simulates heat spreading along a rod whose ends are kept at 100 degrees. In every step, each inner cell becomes the average of itself and its two neighbours.
for i in range(first, last):
new_temps[i] = (temps[i - 1] + temps[i] + temps[i + 1]) / 3
barrier.wait()
Each of the three workers updates its own slice of the
new_temps list. It reads neighbours from the other slices, so all
workers must read the same, complete old state.
def commit():
temps[:] = new_temps
show()
The barrier action copies the new state into temps and prints
it. It runs after all workers have finished the step and before any of them
starts the next one, so no thread ever reads a half-updated list.
$ python heat.py 100.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 100.0 100.0 33.3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 33.3 100.0 100.0 44.4 11.1 0.0 0.0 0.0 0.0 0.0 0.0 11.1 44.4 100.0 100.0 51.9 18.5 3.7 0.0 0.0 0.0 0.0 3.7 18.5 51.9 100.0 100.0 56.8 24.7 7.4 1.2 0.0 0.0 1.2 7.4 24.7 56.8 100.0 100.0 60.5 29.6 11.1 2.9 0.4 0.4 2.9 11.1 29.6 60.5 100.0
asyncio.Barrier
Since Python 3.11 the asyncio module has its own
Barrier for coroutines. Its wait method is a
coroutine, and it has the same parties, n_waiting,
broken, abort, and reset members, but
no action and no timeout.
import asyncio
async def player(name, barrier, delay):
await asyncio.sleep(delay)
print(f'{name} is ready')
await barrier.wait()
print(f'{name} starts')
async def main():
barrier = asyncio.Barrier(3)
async with asyncio.TaskGroup() as tg:
tg.create_task(player('Alice', barrier, 0.3))
tg.create_task(player('Bob', barrier, 0.1))
tg.create_task(player('Carol', barrier, 0.2))
print(f'broken: {barrier.broken}')
asyncio.run(main())
Three players get ready at different times and start the game together.
await barrier.wait()
The coroutine is suspended until all three tasks reach the barrier. A timeout
can be added with asyncio.timeout. The
multiprocessing module also provides a Barrier with
the same interface as the threading one, for synchronizing processes.
$ python async_barrier.py Bob is ready Carol is ready Alice is ready Alice starts Bob starts Carol starts broken: False
Source
threading — Barrier objects
asyncio — Barrier
In this article we have synchronized Python threads with
threading.Barrier. We have used the wait index and the barrier
action, worked in phases, handled timeouts, aborted and reset a barrier, and
used asyncio.Barrier with coroutines. Other synchronization
primitives are covered in the Lock and
Semaphore articles; a barrier built from a
condition variable is shown in barrier with Condition.
Thread pools are covered in ThreadPoolExecutor.
Author
List all Python tutorials.