Consumer Producer Problem

Producer Consumer Problem using Semaphores in Operating System

Producer consumer problem is one classic example of mutual exclusion, process synchronisation using semaphores. It basically synchronises data production and consumption happening simultaneously in a system where there is fixed amount of storage size. The system has the following –

  1. Producer
  2. Consumer
  3. Storage bound of size n
Producer Consumer Problem OS Operating System
Producer Consumer signal and wait OS Operating System

Process of Producer Consumer

The processes is synchronised via a mutex which provides mutual mutual exclusion in the critical section area. There is unit called as empty which defines the number of empty slots in the storage. There is unit called as full which defines the number of full storage slots in the system.

The number of storage slots are initialised as n, the number of empty slots are initialised as n since all slots are empty at the starting similarly the full unit is initialised as 0 as there is no data initially. 

It is important to understand wait and signal first from the image above to understand how the problem works.

Producer

do{

// produce an item
// the producer can only produce if there is atleast 1 empty slot
// thus empty must be >0 and then it also decrements the value wait(empty);
// access to critical section is blocked for consumer section wait(mutex); // place in buffer
// access to critical section is released signal(mutex);
// value of full is incremented signal(full); }while(true)

Consumer

do{

// consumer should wait until there is atleast one item in storage // full value should be greater than 0 and then decremented
wait
(full);
// access to critical section is blocked for producer section wait(mutex); // remove item from buffer
// access to critical section is released for producer section signal(mutex);
​// value of empty is incremented as item was consumer
signal
(empty); // consumes item }while(true)

Please Login/Signup to comment