Skip to content

Barrier (start together)

diagram a Barrier holds everyone until the last one arrives mermaid
Each thread that reaches wait() parks. When the party count is reached, all of them are released together and the barrier resets for the next round. It is how you make several threads start a timed phase at the same moment rather than staggered by however long each took to get there.

A Barrier makes a group of threads wait until all have reached a point.

Use cases:

  • start multiple workers at the same time
  • multi-step simulations
barrier_example.py
import threading
import time
 
barrier = threading.Barrier(3)
 
 
def worker(i: int) -> None:
    time.sleep(0.2 * i)
    print("worker", i, "ready")
    barrier.wait()
    print("worker", i, "started")
 
 
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads:
    t.start()
for t in threads:
    t.join()
  • If a thread fails and never reaches the barrier, others can block.
  • You can set a timeout in barrier.wait(timeout=...).
sketch A barrier holds everyone until the last one arrives p5.js
Three threads reach the barrier at different times and none of them proceeds until the party is complete. Then all three are released in the same instant and each receives a distinct index, exactly one of which is zero -- which is how you designate a single thread to do the once-per-round work. The barrier then resets for the next round.
pch.quizTag pch.quizDefaultTitle
  1. `Barrier(3)`. Two threads have called `wait()`. What are they doing?

    pch.quizShowAnswer

    B — Both blocked, waiting for the third — Verified: with 2 of 3 arrived, neither had passed. A barrier releases nobody until the party count is reached.

  2. What does `barrier.wait()` return?

    pch.quizShowAnswer

    C — A distinct index per thread, exactly one of which is 0 — Each participant gets a different index. Checking for 0 is the standard way to nominate one thread for once-per-round work without needing another lock.

  3. After all threads pass, what state is the barrier in?

    pch.quizShowAnswer

    B — Reset, ready for the next round — A barrier is reusable by design, which is what makes it suited to looping phases — every worker finishes round N before any starts round N+1.

  4. One participant crashes before reaching the barrier. What happens to the others?

    pch.quizShowAnswer

    B — They wait forever unless a timeout was given — There is no default timeout. Pass one to `wait()` and handle `BrokenBarrierError`, which is what the remaining threads receive once the barrier is broken.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading