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 from Producers.
  • 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 from Data representing 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 t chooses a value d from Data and attempts to put it:
    • If the buffer holds fewer than BufCapacity elements, d is appended to the buffer. Then, if any consumers are sleeping in waitSet, one is removed from waitSet; otherwise waitSet is unchanged.
    • Otherwise, t is added to waitSet and the buffer is unchanged.
  • A consumer t attempts 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 from waitSet; otherwise waitSet is unchanged.
    • Otherwise, t is added to waitSet and the buffer is unchanged.
producer-and-consumer
Ready
⌘↵ to submit