Producer-Consumer Problem with Bounded Buffer

Q1. Explain the Producer-Consumer Problem with bounded buffer.

Ans. As an example of how these primitive can be used, let us consider the producer-consumer problem also known as the bounded buffer problem.

Two processes share a common, fixed size buffer. One of them, the producer, puts information into the buffer, and the other one, the consumer, takes it out.

Trouble, arises when the producer wants to put a new item in the buffer, but it is already full. The solution is for the producer to go to sleep, to be awakened when the customer has removed one or more items. Similarly, if the customer wants to remove an item from the buffer and sees that the buffer is empty, it goes to sleep until the producer puts something in the buffer and wakes it up.

#define N 100   /*number of slots in the buffer*/

int count=0;       /*number of items in the buffer*/


void producer(void)


int item;

while(TRUE)                             /*repeat forever*/


item=produce_item();             /*generate next item*/


sleep();                                     /*if buffer is full, go to sleep*/

insert_item(item);                    /*put item in buffer*/

count=count+1;                        /*increment count of items in buffer*/


wakeup(consumer);                 /*was buffer empty?*/




void consume(void)


int item;

while(TRUE)                              /*repeat forever*/



sleep();                                      /*if buffer is empty, go to sleep*/

item=remove_item();                /*take item out of buffer*/

count=count-1;                          /*decrement count of items in buffer*/


wakeup(producer);                   /*was buffer full?*/

consume_item(item);                /*print item*/



The race condition can occur because access to count is unconstrained. The following situation could possibly occur. The buffer is empty and the consumer has just read count to see if it is 0. At that instant, the scheduler decides to stop running the consumer temporarily and start running the producer. The producer inserts an item in the buffer, increments count, and notices that it is now 1. Reasoning that count was just 0, and thus the consumer must be sleeping, the producer calls wakeup to wake the consumer up.

Unfortunately, the consumer is not yet logically asleep, so the wakeup signal is lost. When the consumer next runs, it will test the value of count it previously read, find it to be 0, and go to sleep. Sooner or later the producer will fill up the buffer and also go to sleep. Both will sleep forever.

A quick fix is to modify the rules to add a wakeup waiting bit. When a wakeup is sent to a process that is still awake, this bit is set. Later, when the process tries to go to sleep, if the wakeup waiting bit is on, it will be turned off, but the process will stay awake.

Leave a Reply

Your email address will not be published. Required fields are marked *