Producer–Consumer (Bounded-Buffer) Problem In the Producer–Consumer problem, a producer process generates data items and places them into a finite‐sized buffer, while a consumer removes items from that buffer for processing. The key requirements are:

  1. The producer must block if the buffer is full (no lost items).
  2. The consumer must block if the buffer is empty.
  3. Producer and consumer must not access the buffer simultaneously (mutual exclusion).

Semaphores for Synchronization

A semaphore is an integer variable supporting two atomic operations:

Semaphores can be counting (any nonnegative integer) or binary (0 or 1). They enforce mutual exclusion and coordinate process rendezvous without busy‐waiting if blocking is used .


Solution Using Three Semaphores

Let BufferSize = N. We use:

  1. empty = # of empty slots (initialized to N)
  2. full = # of filled slots (initialized to 0)
  3. mutex = binary semaphore for buffer access (initialized to 1)

Initialization

semaphore empty = N;      // initially all slots empty
semaphore full  = 0;      // no items to consume
semaphore mutex = 1;      // buffer free


Producer Pseudocode