~/problems / Coordination / Barrier

Basics: build a reusable barrier

easy basics ~10 min

threading.Barrier(n) is a meeting point: each thread that calls wait() blocks until n threads have arrived, then all n go on together. Build your own so you know what's inside it.

Implement SimpleBarrier(n):

  • wait() -> int: block until n threads (counting this one) have called wait() in the current round, then return this thread's arrival index in that round: 0 for the first to arrive, n - 1 for the last.
  • The barrier is reusable: once a round of n has gone through, the next n calls to wait() form a new round, and so on. The same threads typically call wait() again straight away.
b = SimpleBarrier(3)
# threads A, B, C call b.wait() in that order:
#   A blocks, B blocks, C arrives -> all three return: A gets 0, B gets 1, C gets 2
# then all three call b.wait() again -> a fresh round with indexes 0, 1, 2

Constraints: n >= 1 (with n = 1, wait() returns 0 at once). Don't use threading.Barrier, and don't sleep or busy-wait.

Show hint

Use a Condition, an arrival count and a generation number: the last arrival resets the count, bumps the generation and calls notify_all(), and the others wait_for the generation to change (not for the count, which has already been reset for the next round).

Topic: Barrier. Rendezvous: n threads wait until all arrive.

0:00
Ctrl ' run · Ctrl ↵ submit
esc