Skip to content

Barrier (start together)

What is a Barrier?

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

Use cases:

  • start multiple workers at the same time
  • multi-step simulations

Example

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()
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()

Notes

  • If a thread fails and never reaches the barrier, others can block.
  • You can set a timeout in barrier.wait(timeout=...)barrier.wait(timeout=...).

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Basic Barrier

Exercise 2 โ€“ Barrier Parties Count

Exercise 3 โ€“ Abort a Barrier

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did