Build a Reusable Thread Rendezvous Point from First Principles
System DesignModel answerLast updated
Implement a cyclic barrier from a mutex and condition variables where N threads block until all arrive, then release together and reset for the next round.
Thread Rendezvous: Build a Cyclic Barrier
You need to coordinate a fixed pool of worker threads so that no thread moves past a checkpoint until every thread in the pool has reached it. Once the last thread arrives, all of them are unblocked simultaneously, and the barrier resets so the same pool can synchronize again on the next iteration — indefinitely, without being recreated.
Design and implement this primitive from scratch.
CyclicBarrier(parties: int)
# parties >= 1, fixed at construction
wait() -> int
# blocks until all `parties` threads have called wait() in this round
# returns the calling thread's arrival index (0 = last to arrive)
# resets automatically so the same object works for round 2, round 3, …
What you may use
Build from a mutex and condition variables (or your language's monitor primitives). Do not reach for a library barrier, latch, phaser, semaphore helper, or anything that already solves the problem for you.
Constraints and rules
parties >= 1, set once at construction.- The barrier must support an unlimited number of consecutive rounds without being recreated or manually reset under normal operation.
- No busy-waiting in the main implementation.
- A thread that arrived in round k must never be counted toward round k+1, and no thread may leave round k before every party in that round has arrived.
- Optional action: support an optional callable passed at construction; it runs exactly once per round, executed by the last thread to arrive, before any waiters are released.
- Broken-barrier semantics: if a waiting thread times out, is interrupted, or the per-round action raises an exception, the barrier enters a broken state; all current and future callers of
wait()in that generation raiseBrokenBarrierErroruntil the barrier is explicitly reset.
What the interviewer is looking for
You are expected to reason through the design out loud before writing code. Cover:
- The data you need to track per round and why.
- How you prevent a fast thread from lapping a slow one (the reuse race).
- How you handle spurious wakeups correctly.
- The failure modes above and how each affects the barrier state.
- An atomics-only (lock-free / spin-based) variant — when would you prefer it, and what does it give up?
- How you would test this: what races does a naive test miss, and how do you expose them?
Hints
Hint 1
The trickiest part is safe reuse. If the last thread of round 1 resets the count to 0 immediately, a fast thread could call wait() again and be counted in round 1's wake-up. Track a 'generation' or 'round ID' alongside the count — each waiter spins on its own generation, not on the global count.
Hint 2
Condition variable waits must always be in a loop: `while not condition: cv.wait()`. Your loop condition should check whether *this round* is done or the barrier is broken, not whether the count reached parties. That way spurious wakeups are harmless and broken-barrier propagation works correctly.
Hint 3
For the atomics-only variant, think about what CAS (compare-and-swap) buys you on the arrival counter and where it falls short. A single atomic decrement tells you who is last, but you still need all other threads to observe the release — consider a flag or a generation counter spun on with a read loop, and be honest about the cost on high-core-count machines.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A cyclic barrier needs to answer two questions atomically: "has everyone arrived?" and "which round am I in?" The first question drives the release; the second prevents the reuse race.
Core data
count # threads still needed in the current round; starts at parties, counts down
generation # increments each time the barrier completes a round
broken # bool; set when the barrier is permanently faulted
All three live under a single mutex. The condition variable is broadcast, not signaled, because every waiter must wake when a round completes.
The reuse race — why generation matters
Imagine parties = 2. Thread A and B finish round 1 and are released. A immediately calls wait() again. If you have only a count, A decrements it to 1 — now B (still processing its own wakeup) might read count == 1 and think round 2 is waiting on one more thread, when in fact it's round 1 finishing. Tracking a generation integer solves this: each waiter captures its generation at entry and waits until either generation > my_gen (round done) or broken.
Python implementation
import threading
class BrokenBarrierError(Exception):
pass
class CyclicBarrier:
def __init__(self, parties: int, action=None):
if parties < 1:
raise ValueError("parties must be >= 1")
self._parties = parties
self._action = action # optional callable, run by last arrival
self._lock = threading.Lock()
self._cv = threading.Condition(self._lock)
self._count = parties # threads still needed this round
self._generation = 0 # increments each completed round
self._broken = False
def wait(self, timeout=None) -> int:
with self._cv:
# Reject immediately if already broken
if self._broken:
raise BrokenBarrierError("barrier is broken")
gen = self._generation
self._count -= 1
arrival_index = self._count # 0 means last to arrive
if self._count == 0:
# This thread is last: run action, then release all
try:
if self._action:
self._action()
except Exception:
self._break_barrier()
self._cv.notify_all()
raise BrokenBarrierError("barrier action raised an exception")
self._next_generation()
self._cv.notify_all()
return arrival_index
# Not last: wait until our generation is done or barrier breaks
deadline = None
if timeout is not None:
import time
deadline = time.monotonic() + timeout
while self._generation == gen and not self._broken:
if deadline is not None:
import time
remaining = deadline - time.monotonic()
if remaining <= 0:
self._break_barrier()
self._cv.notify_all()
raise TimeoutError("timed out waiting at barrier")
self._cv.wait(timeout=remaining)
else:
self._cv.wait()
if self._broken:
raise BrokenBarrierError("barrier is broken")
return arrival_index
def reset(self):
with self._cv:
if self._count != self._parties:
# threads are mid-wait; break first so they can unblock
self._break_barrier()
self._cv.notify_all()
else:
self._broken = False
self._generation += 1 # discard current generation cleanly
def _next_generation(self):
self._count = self._parties
self._generation += 1
self._broken = False
def _break_barrier(self):
self._broken = True
@property
def broken(self):
with self._lock:
return self._broken
Key design decisions
Broadcast, not notify. When the last thread arrives, every waiter must be released. notify_all() is correct; notify() would leave threads sleeping forever.
Loop on generation, not count. The while loop condition is generation == gen and not broken. A thread that wakes for any reason re-checks this before doing anything, making spurious wakeups harmless by construction.
Last-arrives semantics for the action. The action runs inside the lock before _next_generation(). If it raises, _break_barrier() is called before notify_all(), so every waiter sees broken=True when it wakes.
Timeout path breaks the barrier. A single timeout could leave count in an inconsistent state for other threads still waiting. Breaking the whole generation is the safe choice — this mirrors Java's CyclicBarrier behavior.
Atomics-only variant
With atomics you can avoid a mutex on the fast path. Use a single atomic decrement to find the last arrival:
# sketch — not production quality
remaining = count.fetch_sub(1) # atomic
if remaining == 1: # I am last
generation.fetch_add(1) # atomic store-release
count.store(parties) # reset for next round
else:
my_gen = generation.load()
while generation.load() == my_gen: # spin
pass # or cpu_pause()
Trade-offs: spinning burns CPU, which is acceptable when waits are sub-microsecond (e.g., coordinating SIMD pipeline stages on the same socket). On a server with dozens of threads or long waits, spinning wastes cores and should be replaced by an OS-assisted sleep. The atomic version is also harder to extend with timeouts or broken-barrier semantics without reintroducing a lock for the error path.
Testing strategy
A naive test launches N threads, lets them hit the barrier once, and checks they all finish. That test almost never catches the reuse race. Useful approaches:
- Round-trip stress test. Run 100+ rounds with a random
time.sleep()jitter injected after release. Check that no thread from round k is counted in round k+1 by logging arrival generation per thread. - Broken-barrier propagation. Inject a timeout in one thread mid-wait and assert all other waiters in that generation receive
BrokenBarrierError, not a clean release. - One-thread edge case.
parties=1should return immediately every time with no deadlock. - Lapping detection. With parties=2, have thread A loop 1000 times while thread B adds a sleep before every fifth iteration. A correct implementation never deadlocks or miscounts.
Common mistakes
- Using
notify()instead ofnotify_all()— leaves threads permanently blocked. - Checking
count == 0instead ofgeneration != my_genin the wait loop — breaks on spurious wakeups and immediate reuse. - Resetting
countbefore broadcasting — a racing thread can sneak into the new round before old waiters have left. - Forgetting to break the barrier on timeout — the count is now off by one and the barrier will never complete that generation.