Producer and Consumer
In this exercise we will model a fixed-capacity FIFO buffer shared between producer and consumer threads,
using wait()/notify() semantics. A thread that cannot proceed adds itself to a wait
set and goes to sleep. A thread that makes progress wakes one sleeping thread of the opposite role.
Constants
Producers— a non-empty set of producer threads.Consumers— a non-empty set of consumer threads, disjoint fromProducers.BufCapacity— the maximum number of elements the buffer can hold.Data— a non-empty set of values that producers may put into the buffer.
Variables
buffer— a sequence of elements fromDatarepresenting the current buffer contents.waitSet— the set of threads that are currently sleeping.
Initial State
Both buffer and waitSet are empty.
Transitions
Only a thread that is not in waitSet may act.
-
A producer
tchooses a valuedfromDataand attempts to put it:- If the buffer holds fewer than
BufCapacityelements,dis appended to the buffer. Then, if any consumers are sleeping inwaitSet, one is removed fromwaitSet; otherwisewaitSetis unchanged. - Otherwise,
tis added towaitSetand the buffer is unchanged.
- If the buffer holds fewer than
-
A consumer
tattempts to get a value:- If the buffer is non-empty, the head element is removed from the buffer. Then, if any producers are sleeping in
waitSet, one is removed fromwaitSet; otherwisewaitSetis unchanged. - Otherwise,
tis added towaitSetand the buffer is unchanged.
- If the buffer is non-empty, the head element is removed from the buffer. Then, if any producers are sleeping in