Producer/Consumer Workbench
Semaphore Solution
The producer consumer problem is a classic synchronization problem. The
producer and consumer processes share a common buffer (with eight slots in our workbench). The producer executes an infinite loop in which it puts new items into the buffer and the consumer executes and infinite loop in which it removes items from the buffer. The following important conditions have to be satisfied by the producer and consumer:
- At most one process (producer or consumer) may be accessing the shared buffer at any time. This condition is called mutual exclusion.
- When the buffer is full (all eight slots are taken), the producer should be put to sleep. It should only wake up when an empty slot becomes available. This is called synchronization.
- When the buffer is empty, the consumer should be put to sleep. It should only wake up when at least one slot becomes full. This is also called synchronization.
This workbench displays a solution to the consumer-producer problem using three semaphores: mutex, full, and empty.
- Mutex is a binary semaphore that controls access to the shared buffer. It guarantees mutual exclusion on the buffer.
- Full is a counting semaphore that counts the number of full slots.
- Empty is a counting semaphore that counts the number of empty slots.
The workbench that you are about to see, shows the code for the producer and consumer process as well as the shared buffer. You can execute the workbench in a step-by-step mode by pushing the STEP button below each process. This will advance the process through its code. You can see how the buffer contents changes and how the values of the semaphores change as a result of the process execution. A status window below each process indicates if the process is running or sleeping on a particular semaphore. You can also execute the workbench in an animation mode by pushing the ANIMATE button. You will see controls that allow you to change the animation speed and the time it takes for a producer to produce an item and for a consumer to consume an item.
Workbench