Question
Implement the shared buffer as an array of type char. The Producer and Consumer objects must each display the characters when they have accessed the
Implement the shared buffer as an array of type char. The Producer and Consumer objects must each display the characters when they have accessed the shared buffer. You may simplify the problem by defining a buffer with a single text character.
class Semaphore { private int sem; II public synchronized void wait() {
while ( sem <= 0) { try {
swait(); } catch (Exception e) { System.exit(O);};
} II end while
sem--; II decrease value of sem }II end swait II public synchronized void signal() {
sem++;
notify(); } II end signal II II constructor public Semaphore ( int intval) {
sem = intval; II initialize attribute sem } II end class Semaphore
public class Producer extends Thread { private Semaphore mutex; private Semaphore full; private Semaphore empty;
public Producer (Semaphore m, Semaphore f, Semaphore e) { mutex = m; full = f; empty = e;
} II end constructor
public void run() { while (true) {
[ produce an item ] empty.wait(); mutex.waitO;
II are there any empty slots?
II acquire exclusive access [ deposit an item into empty slot of the buffer ]
mutex.signal(); II release mutual exclusion
full.signal(); II increment full slots } II end while loop
} II end run II end class Producer
}
public class Consumer extends Thread { private Semaphore mutex; private Semaphore full; private Semaphore empty;
public Consumer (Semaphore m, Semaphore f, Semaphore e) { mutex = m; full = f; empty = e;
} II end constructor II public run() {
while (true) { full.wait(); mutex.wait();
II are there any full slots?
II acquire exclusive access [ remove an item from a full slot of the buffer ]
mutex.signal(); empty.signal();
[ Consume data item ] } II end while loop
II end while } II end run
}
II end class Consumer
public class ProdconSync { static final int N= 100; II n ber of slots in buffer public static void main (String args[]) {
Semaphore mutex= new Semaphore (1); Semaphore full= new Semaphore (0); Semaphore empty= new Semaphore (N); Producer prod= new Producer (mutex, full, empty); Consumer cons= new Consumer (mutex, full, empty); prod.start();
cons.start(); } II end main } II end class ProdconSync
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started