et 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 consumer has removed one or more items.

Similarly, if the consumer 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.

This approach sounds simple enough, but it leads to the same kinds of race conditions we saw earlier with the spooler directory.

To keep track of the number of items in the buffer, we will need a variable, count. If the maximum number of items the buffer can hold is N, the producer's code will first test to see if count is N. If it is, the producer will go to sleep; if it is not, the producer will add an item and increment count.

The consumer's code is similar: first test count to see if it is 0. If it is, go to sleep; if it is nonzero, remove an item and decrement the counter. Each of the processes also tests to see if the other should be awakened, and if so, wakes it up.

   #define N 100

   int count = 0;

   void producer(void)

   {

   int item;

   while (TRUE)

   {

         item = produce_item();

         if (count = N)

         sleep(); 

         insert_item(item);

         count = count + 1; 

         if (count == 1)

         wakeup(consumer);

     } 

}

void consumer(void)

{

      int item;

      while (TRUE)

   {

     if (count = 0) sleep();

     item = remove_item();

     count = count - 1;

     if (count == N - 1 )

     wakeup(producer);

     consume_item(item);

  }

}

Solving Consumer Producer Problem using Semaphore

#define N 100

typedef int semaphore;

semaphore mutex = 1;

semaphore empty = N;

semaphore full = 0;

void producer(void)

{        

         int item; 

         while (TRUE)

         {

                   item = produce_ttem();

                  down(&empty);

                  down(&mutex);

                  insert-item(item);

                  up(&mutex);

                  up(&fuli);

         }

}

void consumer(void)

{

        int item;

        while (TRUE)

        {

                down(&full);

                down(&mutex);

                item = remove _item();

                up(&mutex);

                up(&empty);

                consume„item(item);

        }

}