progress

~/problems / Coordination / Barrier

Build a reusable barrier

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

threading.Barrier(n) is a meeting point: each thread calling wait() blocks until n have arrived, then all go on together. Build your own.

Implement SimpleBarrier(n) with wait() -> int: block until n threads (this one included) have called wait() this round, then return this thread's arrival index (0 for the first, n - 1 for the last). It's reusable: the next n calls form a new round, often from the same threads right 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

n >= 1 (n = 1 returns 0 at once). Don't use threading.Barrier; don't sleep or busy-wait.

Show hint

a Condition, an arrival count and a generation number: the last arrival resets the count, bumps the generation and calls notify_all(); the others wait_for the generation to change (the count is already reset).

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

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc