Consumer Producer Problem

Producer Consumer Problem using Semaphores in Operating System

The producer-consumer problem is a classic multiprocess synchronization problem. In the Producer-Consumer problem there is a producer, a producer produces some items, and a consumer who consumes the items produced by the producer. Producers and consumers share the same fixed-size memory buffer.  
Producer Consumer Problem in OS

Producer Consumer Problem using Semaphores

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

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 Consumer Signal and Wait

wait(Semaphore s)
{
  while(s == 0);
  s = s-1;
}

signal(Semaphore s)
{
  s = s+1;
}

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)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription