Sub topic 12
Producer-consumer with a bounded buffer
This chapter assumes you know what a process and a thread are, can read C-like pseudocode, and understand that the scheduler can preempt a process between any two instructions. It also assumes you know what a semaphore is, with wait (decrement, block if the value would go below zero) and signal (increment, wake one waiter). Everything here builds on those two operations.
The problem
A producer creates items. A consumer uses them. They share a buffer with a fixed capacity of N slots. The buffer is bounded, so two rules follow:
- The producer must not add an item when all N slots are full.
- The consumer must not remove an item when the buffer is empty.
There is also a third rule. The buffer itself is shared data, so only one process may change it at a time. Without that rule, two processes could update the same index or counter together. This is a race condition.
The problem therefore needs two kinds of synchronisation:
- Condition synchronisation: wait until the buffer is not full (producer) or not empty (consumer).
- Mutual exclusion: only one process touches the buffer structure at a time.
Three semaphores
The standard solution uses three semaphores, each with a clear job.
| Semaphore | Initial value | Meaning | Used for |
|---|---|---|---|
| `empty` | N | Number of free slots | Condition: producer waits when the buffer is full |
| `full` | 0 | Number of filled slots | Condition: consumer waits when the buffer is empty |
| `mutex` | 1 | Binary lock on the buffer | Mutual exclusion |
empty and full are counting semaphores. Their values always satisfy empty + full ≤ N. The sum is less than N only while a process is in the middle of inserting or removing an item.
The solution
semaphore mutex = 1;
semaphore empty = N;
semaphore full = 0;
void producer(void) {
while (1) {
item = produce_item();
wait(empty);
wait(mutex);
insert_item(item);
signal(mutex);
signal(full);
}
}
void consumer(void) {
while (1) {
wait(full);
wait(mutex);
item = remove_item();
signal(mutex);
signal(empty);
consume_item(item);
}
}Read it in three steps for each side.
- Reserve. The producer calls
wait(empty)to claim a free slot. The consumer callswait(full)to claim a filled slot. If none is available, the process blocks here and does not hold the lock. - Operate. Inside
wait(mutex)andsignal(mutex), the process changes the buffer. This critical section is short. - Announce. The producer calls
signal(full)because one more slot is now filled. The consumer callssignal(empty)because one more slot is now free.
Note that produce_item and consume_item sit outside the critical section. Slow work should never be done while holding mutex.
Why the order of wait calls matters
The two wait calls in each routine cannot be swapped. Suppose the producer does wait(mutex) first and then wait(empty). Consider this sequence:
- The buffer is full, so
empty = 0. - The producer runs
wait(mutex)and gets the lock. - The producer runs
wait(empty)and blocks, still holdingmutex. - The consumer runs
wait(full), which succeeds, and thenwait(mutex), which blocks because the producer holds it.
Neither process can continue. The producer waits for a free slot that only the consumer can create. The consumer waits for a lock that only the producer can release. This is a deadlock.
The same problem exists on the consumer side with an empty buffer if wait(mutex) comes before wait(full).
The order of signal calls is different. Swapping signal(mutex) and signal(full) does not cause deadlock or incorrect results. It may only change which process runs next.
Tracing an example
Take N = 2, starting with empty = 2, full = 0, mutex = 1. The producer runs three times before the consumer runs.
| Step | Action | empty | full | mutex | Note |
|---|---|---|---|---|---|
| 0 | Initial state | 2 | 0 | 1 | Buffer empty |
| 1 | Producer inserts item A | 1 | 1 | 1 | |
| 2 | Producer inserts item B | 0 | 2 | 1 | Buffer full |
| 3 | Producer calls `wait(empty)` | 0 | 2 | 1 | Producer blocks and holds no lock |
| 4 | Consumer removes A | 0 → 1 | 1 | 1 | `signal(empty)` wakes the producer |
| 5 | Producer finishes inserting C | 0 | 2 | 1 | Woken producer takes the freed slot |
At step 4, the consumer's signal(empty) raises the value to 1 and wakes the blocked producer. The producer's wait then completes, and the count returns to 0. Step 5 shows the final state.
The invariant to check at each step is that full equals the number of items in the buffer, and empty equals the number of free slots. Reserved slots are counted as taken while the operation is still in progress.
Edge cases
- Single producer and single consumer. With a circular buffer where the producer only changes
inand the consumer only changesout, the mutex is technically not needed. The two counting semaphores already prevent overrun and underrun. The mutex becomes necessary with several producers or several consumers, because they would shareinorout. - Multiple producers. Without
mutex, two producers could read the same value ofinand write to the same slot, losing an item. - Buffer size 1. The solution still works.
emptyandfullalternate between 1 and 0, so the processes take strict turns. - Using only a mutex. A producer could lock the buffer, find it full, and have no safe way to wait. It would have to release the lock and retry in a loop (busy waiting). Counting semaphores avoid this.
- Wrong initial values. If
emptystarts at 0, the producer blocks forever. Iffullstarts above 0, the consumer would read items that were never produced.
Counting outcomes
GATE questions often ask for the possible values of a semaphore, or how many items remain. Use the invariants:
- Items in the buffer = number of completed inserts − number of completed removes.
full= items in the buffer, andempty= N − items in the buffer, when no process is in mid-operation.- If a producer completes P iterations and a consumer completes C iterations, then
full = P − Candempty = N − P + C, with0 ≤ P − C ≤ N.
For example, with N = 5, 8 inserts and 6 removes give full = 2 and empty = 3.
Summary of the design
Exercise
A bounded buffer has N = 4 slots. The semaphores are mutex = 1, empty = 4, full = 0. After 10 completed producer iterations and 7 completed consumer iterations (no process is mid-operation), what are the values of empty and full? Then say what happens if the producer routine is changed to call wait(mutex) before wait(empty).
Show answer
full = 10 − 7 = 3 and empty = 4 − 3 = 1. With the swapped order, the producer can acquire mutex and then block on wait(empty) when the buffer is full. The consumer then blocks on wait(mutex), which the producer holds. Neither can continue, so the system deadlocks.
Exercise
Why can a producer-consumer solution with exactly one producer and one consumer work without the mutex semaphore, but a solution with two producers cannot?
Show answer
With one producer and one consumer, the producer alone changes the in index and the consumer alone changes the out index, and the empty and full semaphores already keep them from overrunning or underrunning each other. With two producers, both can read the same value of in before either updates it, so they write to the same slot and one item is lost. The mutex makes the read-write-update of in atomic.