One solution for Barrier Synchronization Problem
(shared counter using Hoare-Style Monitor)
monitor Barrier {
private:
int n; // number of processes
int in; // number before barrier
int out; // number after barrier
// monitor invariant:
// (0 = in = n) and (0 = out = n) and (in = 0 or out = n)
condition canEnter; // out = n
condition canExit; // in = n
public:
Barrier(int num) {
n = num;
in = 0;
out = n;
increasing = 1;
};
entry void Arrive(void) {
while (out < n) canEnter.wait();
in++;
while (in < n) canExit.wait();
out = 0;
canExit.notifyAll();
out++;
if (out == n) {
in = 0;
canEnter.notifyAll();
}
}
}