Instead of giving you an answer, I'll give you a hint. Let me know if you want me the full answer.
First, fix your code according to my answer to your other question—if I'm right about its flaws, that is :)
Second, imagine that we have m threads and a barrier(n) where m >= 2n, each thread doing
while True:
noncritical()
barrier.enter() # e.g. phase1()
critical()
barrier.leave() # e.g. phase2()
If you implement enter() and leave() as I have suggested, you may have 2n threads in the critical section. To fix this problem, I have come up with the following construct:
class N_At_A_Time_Barrier(n):
fields:
occupied = Semaphore(n)
barrier = Barrier(n)
method enter():
occupied.down()
barrier.down()
method leave():
occupied.up()
In the terminology of The Little book of Semaphores, occupied is a Multiplex. The hint: the solution to the H2O problem is very similar to this. My solution uses a Barrier(1+2) and... something else :)
(Footnote: there are more efficient ways of implementing an N_At_A_Time_Barrier, where each group of n threads has their own shared state set up by the first thread to arrive, but that's a lot more complicated and I don't think it relates to the H2O problem as neatly.)