Here is my implementation of CyclicBarrier
public class CyclicBarrier {
int numParties, arrived;
Semaphore mutex;
Semaphore barrier1, barrier2;
public CyclicBarrier(int parties) {
// TODO: The constructor for this CyclicBarrier
this.numParties = parties; //Total number of threads
this.arrived = 0; //Initially zero
mutex = new Semaphore(1);
barrier1 = new Semaphore(0); //Initially Closed
barrier2 = new Semaphore(1); //Initially Open
}
public void await() throws InterruptedException {
phase1(); //Phase 1 ensures that all threads wait at the barrier
phase2(); //Phase 2 resets the Cyclic barrier for reuse
}
void phase1() throws InterruptedException {
mutex.acquire();
arrived++;
if(arrived == numParties){
barrier2.acquire(); // Close barrier 2
barrier1.release(); // Release one thread from barrier 1
}
mutex.release();
barrier1.acquire();
barrier1.release();
}
void phase2() throws InterruptedException {
mutex.acquire();
arrived--;
if(arrived == 0){
barrier1.acquire(); // Close barrier 1
barrier2.release(); // Let one thread go through barrier 2
}
mutex.release();
barrier2.acquire();
barrier2.release(); // Each thread passes through will signal one other thread
}
}
Two questions
- Is this correct?
- If I only call phase1 from the class that consumes this barrier, does it become a countdown latch?