+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

Wei-Lun Hungadd chap. 2 and 3df69975

master
926 B28 linesraw
1class BoundedBuffer {
2    final int size = 10;
3    Object[] buffer = new Object[size];
4    int inBuf = 0, outBuf = 0;
5    BinarySemaphore mutex = new BinarySemaphore(true);
6    CountingSemaphore isEmpty = new CountingSemaphore(0);
7    CountingSemaphore isFull = new CountingSemaphore(size);
8
9    public void deposit(Object value) {
10        isFull.P();// wait if buffer is full
11        mutex.P(); // ensures mutual exclusion
12        buffer[inBuf] = value; // update the buffer
13        inBuf = (inBuf + 1) % size;
14        mutex.V();
15        isEmpty.V();  // notify any waiting consumer
16    }
17    public Object fetch() {
18        Object value;
19        isEmpty.P(); // wait if buffer is empty
20        mutex.P();  // ensures mutual exclusion
21        value = buffer[outBuf]; //read from buffer
22        outBuf = (outBuf + 1) % size;
23        mutex.V();
24        isFull.V(); // notify any waiting producer
25        return value;
26    }
27}
28