Sub topic 3
Producer-Consumer, Readers-Writers, Dining Philosophers, Monitors, and Deadlock
This chapter assumes you know process and thread basics, how a context switch works, and how semaphores support wait (P) and signal (V). Each classic problem below tests one synchronisation idea that GATE questions often ask about.
Producer-Consumer with a Bounded Buffer
A bounded buffer is a fixed-size queue shared by a producer, which adds items, and a consumer, which removes them. Three semaphores coordinate the work: empty counts free slots, full counts filled slots, and mutex protects the buffer itself.
import threading
from collections import deque
N = 3
buffer = deque()
mutex = threading.Semaphore(1)
empty = threading.Semaphore(N)
full = threading.Semaphore(0)
def producer():
for i in range(5):
empty.acquire()
mutex.acquire()
buffer.append(i)
mutex.release()
full.release()
def consumer():
for _ in range(5):
full.acquire()
mutex.acquire()
item = buffer.popleft()
mutex.release()
empty.release()
print("consumed", item)
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join(); t2.join()Readers-Writers and Dining Philosophers
The readers-writers problem allows many readers to read at once, but a writer needs exclusive access. The first solution favours readers, so writers can starve.
Dining philosophers is a model of resource contention. Five philosophers share five forks, and each needs two adjacent forks to eat. If every philosopher picks up the left fork at once, all wait forever for the right fork.
Monitors and Condition Variables
A monitor bundles shared data, a lock, and condition variables. A condition variable lets a thread sleep until another thread signals a change. Unlike a semaphore, wait on a condition variable releases the monitor lock while the thread sleeps.
Deadlock and Priority Inversion
| Hazard | Cause | Fix |
|---|---|---|
| Deadlock from wrong ordering | Producer waits on `mutex` before `empty`, so it holds the lock while blocked | Acquire the counting semaphore first, then `mutex` |
| Priority inversion | Low-priority task holds a lock that a high-priority task needs, and a medium-priority task preempts the low one | Priority inheritance |
Priority inversion matters because the high-priority task waits on work that it cannot run, even though no task is doing anything wrong.
Exercise
In the producer-consumer code above, what happens if the producer calls mutex.acquire() before empty.acquire() and the buffer is full?
Show answer
The producer holds mutex while it waits for an empty slot. The consumer then needs mutex to remove an item, so both threads block forever. This is deadlock from wrong semaphore ordering.