Producer-Consumer Problem

Producer-Consumer Problem using Semaphore

Producer() {

put(item) {

P(empty); // for wait, Get an empty count, block if unavailable
P(mutex); // lock critical section: shared buffer
<<< critical section: Put item into shared buffer >>>
V(mutex); // unlock critical section
V(full); // for signal, increase number of full count

}

}

Consumer() {

take () {

P(full); // for wait, Get a full count, block if unavailable
P(mutex);
<<< critical section: Take item from shared buffer >>>
V(mutex);
V(empty); // for signal, increase number of empty count
return item;

}

}

Producer-Consumer Problem using Monitor

Producer() {

synchronized put(item) {

while(count >= buffer.length) { wait(); } // wait if buffer is full
count++
<<< critical section: Put iteminto shared buffer >>>
notifyAll(); // signal

}

}

Consumer() {

synchronized take () {

while(count <=0) { wait(); } // wait if buffer is empty
count- –
<<< critical section: Take itemfrom shared buffer >>>
notifyAll(); // signal
return item;

}

}