Python barrier with Condition
last modified November 29, 2026 Python 3.15
In this article we show how to use threading.Condition and
build a thread barrier with it, step by step.
Python has a ready-made threading.Barrier,
and there is no BoundedBarrier class in the standard library.
Writing our own barrier is still a good exercise: it shows how a condition
variable works and why the standard primitives are built the way they are.
In practice, use threading.Barrier.
A condition variable lets threads wait until some state becomes
true. It is tied to a lock. A thread holding the
lock checks the state; if it is not ready, the thread calls
wait, which releases the lock and blocks. Another thread changes
the state under the lock and calls notify or
notify_all to wake the waiting threads. A woken thread
reacquires the lock before wait returns.
Wait and notify
In the first program one thread waits for data that another thread prepares.
import threading
import time
cond = threading.Condition()
ready = False
def consumer():
with cond:
while not ready:
print('consumer: waiting')
cond.wait()
print('consumer: data is ready')
def producer():
global ready
time.sleep(0.5)
with cond:
ready = True
print('producer: notifying')
cond.notify()
threads = [threading.Thread(target=consumer),
threading.Thread(target=producer)]
for t in threads:
t.start()
for t in threads:
t.join()
The shared state is the ready flag. Both threads work with it
only inside with cond, which acquires the condition's lock.
while not ready:
print('consumer: waiting')
cond.wait()
The consumer checks the flag in a loop. The wait call releases
the lock, so the producer can enter its own with cond block.
The loop is needed because the state may no longer hold when
wait returns: between the notification and the moment the
woken thread gets the lock back, another thread may have changed it.
with cond:
ready = True
print('producer: notifying')
cond.notify()
The producer changes the state and then notifies. The notify
method wakes one waiting thread; it must be called with the lock held.
$ python condition_basic.py consumer: waiting producer: notifying consumer: data is ready
wait_for
The wait_for method takes a predicate and contains the loop
from the previous example. It also accepts a timeout and returns the last
value of the predicate.
import threading
import time
cond = threading.Condition()
stock = 0
def customer(name, wanted, timeout):
with cond:
ok = cond.wait_for(lambda: stock >= wanted, timeout=timeout)
print(f'{name}: wants {wanted}, stock {stock}, ok: {ok}')
threads = [threading.Thread(target=customer, args=('ann', 3, 2)),
threading.Thread(target=customer, args=('bob', 8, 2))]
for t in threads:
t.start()
for _ in range(5):
time.sleep(0.2)
with cond:
stock += 1
cond.notify_all()
for t in threads:
t.join()
Two customers wait for goods. The main thread adds one item every 0.2 seconds, five in total.
ok = cond.wait_for(lambda: stock >= wanted, timeout=timeout)
Each customer waits until there is enough stock, but at most two seconds. The predicate is checked with the lock held.
with cond:
stock += 1
cond.notify_all()
The two customers wait for different things, so the main thread wakes all of
them with notify_all, and each checks its own predicate. With
notify, the woken thread could be the one whose predicate is
still false. Ann gets her goods; Bob times out with five items in stock.
$ python wait_for.py ann: wants 3, stock 3, ok: True bob: wants 8, stock 5, ok: False
A one-shot barrier
A barrier is a condition: "all parties have arrived". A counter records the arrivals, and the last thread to arrive wakes up the others.
import threading
import time
class OneShotBarrier:
def __init__(self, parties):
self.parties = parties
self.count = 0
self.cond = threading.Condition()
def wait(self):
with self.cond:
self.count += 1
if self.count == self.parties:
self.cond.notify_all()
else:
self.cond.wait_for(lambda: self.count == self.parties)
barrier = OneShotBarrier(3)
start = time.perf_counter()
def worker(name, delay):
time.sleep(delay)
print(f'{name}: arrived at {time.perf_counter() - start:.1f} s')
barrier.wait()
print(f'{name}: passed at {time.perf_counter() - start:.1f} s')
threads = [threading.Thread(target=worker, args=(f'w{i}', i * 0.3))
for i in range(1, 4)]
for t in threads:
t.start()
for t in threads:
t.join()
Three workers arrive at 0.3, 0.6, and 0.9 seconds.
self.count += 1
if self.count == self.parties:
self.cond.notify_all()
else:
self.cond.wait_for(lambda: self.count == self.parties)
Each thread increments the counter. The last one notifies; the others wait until the counter reaches the number of parties. All three pass at 0.9 seconds; the order of the last three lines can differ between runs.
This barrier works only once. After the first round the counter stays at
the number of parties, so later calls to wait would not block.
$ python one_shot.py w1: arrived at 0.3 s w2: arrived at 0.6 s w3: arrived at 0.9 s w3: passed at 0.9 s w1: passed at 0.9 s w2: passed at 0.9 s
Resetting the counter
To reuse the barrier, the last thread must reset the counter. Doing it in the obvious way introduces a bug.
import threading
class NaiveBarrier:
def __init__(self, parties):
self.parties = parties
self.count = 0
self.cond = threading.Condition()
def wait(self):
with self.cond:
self.count += 1
if self.count == self.parties:
self.count = 0
self.cond.notify_all()
return True
return self.cond.wait_for(lambda: self.count == self.parties,
timeout=1)
barrier = NaiveBarrier(2)
def worker(name):
for phase in range(1, 3):
passed = barrier.wait()
print(f'{name}: phase {phase}, passed: {passed}')
threads = [threading.Thread(target=worker, args=(f'w{i}',))
for i in range(1, 3)]
for t in threads:
t.start()
for t in threads:
t.join()
Two workers go through two phases. To keep the program from hanging, the
waiting threads give up after one second, and wait returns
whether the thread passed normally.
if self.count == self.parties:
self.count = 0
self.cond.notify_all()
The last thread resets the counter before the others get a chance to run.
When a waiting thread wakes up, wait_for checks the predicate
again, finds the counter at zero, and goes back to sleep. Every round, the
woken thread misses its own wakeup and times out. Without the timeout, the
program would deadlock.
$ python naive_reuse.py w2: phase 1, passed: True w1: phase 1, passed: False w1: phase 2, passed: True w2: phase 2, passed: False
A reusable barrier
The fix is to wait for an event rather than for a count. A generation number identifies the current round. The last thread increments it; the others wait until it changes. The counter can then be reset safely.
import threading
import time
class ReusableBarrier:
def __init__(self, parties):
self.parties = parties
self.count = 0
self.generation = 0
self.cond = threading.Condition()
def wait(self):
with self.cond:
gen = self.generation
self.count += 1
if self.count == self.parties:
self.count = 0
self.generation += 1
self.cond.notify_all()
else:
self.cond.wait_for(lambda: self.generation != gen)
barrier = ReusableBarrier(3)
lock = threading.Lock()
log = []
def worker(name, delay):
for phase in range(1, 4):
time.sleep(delay)
with lock:
log.append((phase, name))
barrier.wait()
threads = [threading.Thread(target=worker, args=(f'w{i}', i * 0.05))
for i in range(1, 4)]
for t in threads:
t.start()
for t in threads:
t.join()
for phase, name in log:
print(f'phase {phase}: {name}')
Three workers go through three phases at different speeds and log the phase they have finished.
gen = self.generation ... self.cond.wait_for(lambda: self.generation != gen)
Each thread remembers the generation it arrived in. Once the generation changes, the thread is released, whatever happens to the counter afterwards. A fast thread that enters the next round and increments the counter does not affect threads still waking up from the previous one.
The log shows that no worker starts a phase before all have finished the previous one, although the first worker is three times faster than the third.
$ python generation.py phase 1: w1 phase 1: w2 phase 1: w3 phase 2: w1 phase 2: w2 phase 2: w3 phase 3: w1 phase 3: w2 phase 3: w3
Arrival index and action
The standard Barrier returns an arrival index from
wait and can run an action when the barrier trips. Both
are easy to add.
import threading
import time
class Barrier:
def __init__(self, parties, action=None):
self.parties = parties
self.action = action
self.count = 0
self.generation = 0
self.cond = threading.Condition()
def wait(self):
with self.cond:
gen = self.generation
index = self.count
self.count += 1
if self.count == self.parties:
if self.action:
self.action()
self.count = 0
self.generation += 1
self.cond.notify_all()
else:
self.cond.wait_for(lambda: self.generation != gen)
return index
results = {}
def report():
print(f'action: {len(results)} readings, sum {sum(results.values())}')
barrier = Barrier(3, action=report)
def worker(name, delay, value):
time.sleep(delay)
results[name] = value
index = barrier.wait()
print(f'{name}: index {index}')
sensors = [('north', 0.1, 12), ('south', 0.2, 17), ('east', 0.3, 9)]
threads = [threading.Thread(target=worker, args=s) for s in sensors]
for t in threads:
t.start()
for t in threads:
t.join()
Three sensors store a reading and wait at the barrier. The action reports the readings once all three are in.
index = self.count
self.count += 1
if self.count == self.parties:
if self.action:
self.action()
The index is the number of threads that arrived earlier, so it runs from 0 to
parties - 1, like in CPython's Barrier. The action
runs in the last thread, before any thread is released, so it sees all
readings and no thread can change them while it runs. The order of the index
lines can differ between runs.
$ python index_action.py action: 3 readings, sum 38 east: index 2 south: index 1 north: index 0
Timeouts and a broken barrier
If one party never arrives, the others wait forever. The standard barrier
handles this with a broken state: when a thread times out, the
barrier breaks and every waiting and future call raises
BrokenBarrierError.
import threading
import time
class BrokenBarrierError(RuntimeError):
pass
class Barrier:
def __init__(self, parties):
self.parties = parties
self.count = 0
self.generation = 0
self.broken = False
self.cond = threading.Condition()
def wait(self, timeout=None):
with self.cond:
if self.broken:
raise BrokenBarrierError
gen = self.generation
self.count += 1
if self.count == self.parties:
self.count = 0
self.generation += 1
self.cond.notify_all()
return
done = self.cond.wait_for(
lambda: self.generation != gen or self.broken, timeout)
if self.broken or not done:
self.broken = True
self.cond.notify_all()
raise BrokenBarrierError
barrier = Barrier(3)
def worker(name, delay, timeout):
time.sleep(delay)
try:
barrier.wait(timeout)
print(f'{name}: passed')
except BrokenBarrierError:
print(f'{name}: barrier broken')
workers = [('w1', 0, 0.5), ('w2', 0.1, None), ('w3', 1.0, None)]
threads = [threading.Thread(target=worker, args=w) for w in workers]
for t in threads:
t.start()
for t in threads:
t.join()
The first worker waits at most half a second. The third worker arrives only after one second.
done = self.cond.wait_for(
lambda: self.generation != gen or self.broken, timeout)
if self.broken or not done:
self.broken = True
self.cond.notify_all()
raise BrokenBarrierError
A waiting thread is released either by a new generation or by a broken
barrier. A thread that times out marks the barrier broken and wakes the
others, so they do not wait for a round that cannot complete. A real
implementation would also lower the counter and offer reset and
abort methods, as the standard barrier does.
if self.broken:
raise BrokenBarrierError
A thread that arrives at a broken barrier fails at once.
$ python broken.py w1: barrier broken w2: barrier broken w3: barrier broken
A countdown latch
A condition variable can express other primitives that the
threading module lacks. A countdown latch is
opened by a number of events, not by a number of waiting threads. The
threads that count down do not wait, and the latch cannot be reused.
import threading
import time
class CountDownLatch:
def __init__(self, count):
self.count = count
self.cond = threading.Condition()
def count_down(self):
with self.cond:
if self.count > 0:
self.count -= 1
if self.count == 0:
self.cond.notify_all()
def wait(self, timeout=None):
with self.cond:
return self.cond.wait_for(lambda: self.count == 0, timeout)
services = {'database': 0.3, 'cache': 0.1, 'mail': 0.2}
latch = CountDownLatch(len(services))
start = time.perf_counter()
def init(name, delay):
time.sleep(delay)
print(f'{time.perf_counter() - start:.1f} s {name} ready')
latch.count_down()
for name, delay in services.items():
threading.Thread(target=init, args=(name, delay)).start()
if latch.wait(timeout=2):
print(f'{time.perf_counter() - start:.1f} s server started')
A server waits until its three services are ready, but at most two seconds.
def count_down(self):
with self.cond:
if self.count > 0:
self.count -= 1
if self.count == 0:
self.cond.notify_all()
Each service counts the latch down and continues. The last count wakes the
waiting threads. The wait method returns the result of
wait_for, so the caller knows whether the latch opened or the
timeout expired.
$ python latch.py 0.1 s cache ready 0.2 s mail ready 0.3 s database ready 0.3 s server started
Source
threading — Condition objects
threading — Barrier objects
CPython threading.py source
In this article we have used threading.Condition to build a
thread barrier step by step. We have used wait,
notify, and wait_for, fixed a lost wakeup with a
generation number, added an arrival index, an action, and a broken state,
and written a countdown latch. The standard barrier is covered in
Barrier; locks and semaphores in
Lock and Semaphore.
Author
List all Python tutorials.