Producer consumer problem

 

Introduction:

Producer consumer problem is also called as bounded-buffer problem. This is the classic example for 
thread synchronization. 

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. The same memory buffer is shared by both producers and consumers which is of fixed-size. 

The intention of the solution is to provide the shared memory resource between producer and consumer threads, and synchronization between these threads , and exclusive access to the shared buffer.  




Key points:

  • The producer should produce data only when the buffer is not full. If buffer is full, the producer is not allowed to store any data into the memory buffer until free space available.
  • Consumer can consume the data only when the buffer is not empty. If buffer is empty, the consumer is not allowed to use any data from the memory buffer until some data is available in the buffer.
  • Accessing memory buffer should not be allowed to producer and consumer at the same time.
Two solutions are provided here.