Producer Consumer Problem

  • August 28, 2021
  • Aashish Mishra
  • The producer consumer problem is a synchronization problem.
  • There is one Producer in the producer-consumer problem, Producer is producing some items, whereas there is one Consumer that is consuming the items produced by the Producer. The same memory buffer is shared by both producers and consumers which is of fixed-size.
  • The task of the Producer is to produce the item, put it into the memory buffer, and again start producing items. Whereas the task of the Consumer is to consume the item from the memory buffer.

Below are a few points that considered as the problems occur in Producer-
Consumer:

  • The producer should produce data only when the buffer is not full. In case it is found that the buffer is full, the producer is not allowed to store any data into the memory buffer.
  • Data can only be consumed by the consumer if and only if the memory buffer is not empty. In case it is found that the buffer is empty, the consumer is not allowed to use any data from the memory buffer.
  • Accessing memory buffer should not be allowed to producer and consumer at the same time.

Problem Statement – We have a buffer of fixed size. A producer can produce
an item and can place in the buffer. A consumer can pick items and can
consume them. We need to ensure that when a producer is placing an item in
the buffer, then at the same time consumer should not consume any item. In this problem, buffer is the critical section.

To solve this problem, we need two counting semaphores – Full and Empty.
“Full” keeps track of number of items in the buffer at any given time and
“Empty” keeps track of number of unoccupied slots.

Initialization of semaphores –
mutex = 1

Full = 0 // Initially, all slots are empty. Thus full slots are 0
Empty = n // All slots are empty initially
Producer = check overflow(at least one place empty)
Consumer = check underflow (at least one item present in the buffer)

Solution for Producer –

do{

wait(empty);
wait(mutex);

signal(mutex);
signal(full);

}while(true)

When producer produces an item then the value of “empty” is reduced by 1
because one slot will be filled now. The value of mutex is also reduced to
prevent consumer to access the buffer. Now, the producer has placed the item
and thus the value of “full” is increased by 1. The value of mutex is also
increased by 1 because the task of producer has been completed and
consumer can access the buffer.

Solution for Consumer –

do{
wait(full);
wait(mutex);

signal(mutex);
signal(empty);

}while(true)

As the consumer is removing an item from buffer, therefore the value of “full” is
reduced by 1 and the value is mutex is also reduced so that the producer
cannot access the buffer at this moment. Now, the consumer has consumed
the item, thus increasing the value of “empty” by 1. The value of mutex is also
increased so that producer can access the buffer now.