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 untilnthreads (counting this one) have calledwait()in the current round, then return this thread's arrival index in that round:0for the first to arrive,n - 1for the last.- The barrier is reusable: once a round of
nhas gone through, the nextncalls towait()form a new round, and so on. The same threads typically callwait()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).