Producer-Consumer Problem Using Semaphores
The Solution to producer-consumer problem use three semaphores namely- full, empty and mutex.
The semaphore 'full' is utilized for counting the number of slots in the buffer that are full. The 'empty' for calculate the number of slots that are empty and semaphore 'mutex' to make sure that the producer and consumer don't access modifiable shared section of the buffer simultaneously.
Initialization
- Set full buffer slots to 0.
i.e., semaphore Full = 0.
- Set empty buffer slots to N.
i.e., semaphore empty = N.
- For control access to critical section set mutex to 1.
i.e., semaphore mutex = 1.
Producer ( )
WHILE (true)
produce-Item ( );
P (empty);
P (mutex);
enter-Item ( )
V (mutex)
V (full);
Consumer ( )
WHILE (true)
P (full)
P (mutex);
remove-Item ( );
V (mutex);
V (empty);
consume-Item (Item)