Monitor Based 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:
This workbench displays a solution to the consumer-producer problem using the monitor called ProducerConsumer. The monitor has two procedures: EnterItem and RemoveItem. The monitor has two condition variables: full and empty. A count variable indicates the number of full slots in the buffer. This variable is a monitor variable and can only be accessed by one of the two monitor procedures.
The workbench that you are about to see, shows the code for the producer and consumer process, the code for the monitor, and 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. When a process is waiting on a condition variable a bullet corresponding to the process will be displayed inside the monitor code to indicate where the process is supposed to reenter the monitor. You can see how the buffer contents changes and how the value count variable changes 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 START 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.
- 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.