##### Producer Consumer Problem

Bounded Buffer /Producer and ConsumerProblem

We have two processes named as Producer and Consumer. There is finite size of buffer or circular queue with two pointers ‘in’ and ‘out’.

Producer process produce items and fill into buffer using ‘in’ pointer and consumer process consume process from the buffer using ‘out’ pointer. We must maintain count for empty and full buffers. Also, there should be synchronization between producing items and consuming items otherwise processes go to sleep an item is available to consume or a slot is available to put item.

Producer consumer problem can be solved using semaphores or monitors. Here we see solution using semaphores. There are three semaphores: full, empty, and mutex. ‘Full’ counts number of full slots, ‘empty’ counts number of empty slots, and ‘mutex’ enforces mutual exclusion condition.

 Shared Data: Semaphore mutex = 1 ;    /* for mutual exclusion */ Semaphore full = 0 ;   /* counts number of full slots, initially none */ Semaphore empty = n ;  /* counts number of empty slots, initially all */ Producer Process: Producer () { While (true) { Produce_item (item) ; /* produce new item */ P (empty) ;    /* decrease number of empty slots */ P (mutex) ;    /* enter into critical section */ Add_item (item) ;   /* item added in the buffer */ V (mutex) ;     /* end the critical section */ V (full) ;   /* increase number of full slots */ } } Consumer Process: Consumer () { while() { P (full) ;   /* decrease number of full slots */ P (mutex) ;  /* enter into critical section */ Remove_item () ;  /* item removed from the buffer */ V (mutex) ;  /* end the critical section */ V (empty) ;   /* increase the number of empty slots */ } }