You are asked to implement barrier synchronization across n processes. For this purpose, you are given a class that implements the CounterState interface, which provides the ability to perform atomic read, write, and increment-and-read operations on counters.
interface CounterState {
int readCounter(int index);
int incAndReadCounter(int index);
void writeCounter(int index, int value);
}
We are asking you to implement a Barrier class that uses the CounterState interface. What is the number of counters you would need? You can use the below skeleton for your Barrier class:
class Barrier {
...
CounterState state = null;
public Barrier(CounterState state) {
this.state = state;
}
void barrier (int n) {
...
}
}
Here is how one might use the Barrier class and the CounterState' class:
class BarrierTestThread extends Thread
{
private int n = 1;
private CounterState state = null;
private Barrier barrier = null;
volatile boolean shutdown = false;
public BarrierTestThread(int n, CounterState state)
{
this.n = n;
this.state = state;
barrier = new Barrier(state);
}
public void shutdown()
{
shutdown = false;
}
@Override
public void run()
{
while(!shutdown) {
System.err.println("A");
barrier.barrier(n);
System.err.println("B");
barrier.barrier(n);
}
}
}
public class BarrierTest
{
public static void main(String[] args) throws Exception
{
CounterState state = new CounterStateImpl();
BarrierTestThread[] threads = new BarrierTestThread[10];
for (int i=0; i<threads.length; ++i)
threads[i] = new BarrierTestThread(threads.length, state);
for (int i=0; i<threads.length; ++i)
threads[i].start();
Thread.sleep(5*1000);
for (int i=0; i<threads.length; ++i)
threads[i].shutdown();
for (int i=0; i<threads.length; ++i)
threads[i].join();
}
}
See the solution here.