Lesson 6 · Synchronization and deadlocks

Producer Consumer Problem

A producer fills a bounded buffer, a consumer drains it, and neither may run past the other. Three semaphores solve it — and swapping two lines deadlocks it.

Producer Consumer Problem concept diagramA visual explanation of the layout and operations shown in this lesson.one buffer, two semaphores: empty counts free slots, full counts itemsproducerwrites an itemconsumertakes an itembufferN = 5·0B1C2D3·4in = 4out = 1empty = 2free slots — producer waits on 0full = 3items ready — consumer waits on 0mutex guards the slot itself; empty and full do the waiting
1

One Buffer, Two Processes

The producer-consumer problem is a classic operating system exercise in process synchronization. A producer process generates data and places it into a shared, fixed-size buffer, while a consumer process removes that data and uses it. The problem is to make both run concurrently without corrupting the buffer or losing data.

It is also called the bounded buffer problem, because the buffer holds at most N items. Two conditions must hold at all times: the producer must not insert into a full buffer, and the consumer must not remove from an empty one.

The difficulty is that the buffer and its indices are shared data. A process cannot simply test whether the buffer is full and then act on the answer, because another process may change it in between — that is a race condition.

  • It is a synchronization problem, not a data-structure problem — the buffer itself is trivial
  • The producer must wait when the buffer is full; the consumer must wait when it is empty
  • Both processes access the same indices, so insertion and removal need mutual exclusion
  • It is the standard test of whether a primitive can express counting, not just locking
2

The Three Semaphores and What Each One Counts

  1. empty = N: a producer must take one before inserting.
  2. full = 0: a consumer must take one before removing.
  3. mutex = 1: whoever holds it owns the indices.

The standard solution uses three semaphores, and confusing their roles is the most common mistake in an exam answer.

wait() decrements and blocks at zero; signal() increments and may wake a waiter. So wait(empty) means claim a free slot, or block until one exists: it is not a lock, it is a counter of a resource.

  • empty and full are counting semaphores, range 0..N
  • mutex is binary — it never counts anything
  • empty + full ≤ N at all times
3

The Producer and Consumer Code

  1. wait(empty) – the producer claims a free slot. If empty is 0 the buffer is full, so the producer blocks here rather than overwriting data.
  2. wait(mutex) – only now does it take the lock. Claiming the slot first, the lock second, is what keeps the two waits from deadlocking.
  3. insert the item: the only work done while holding mutex, kept as short as possible.
  4. signal(mutex) – release the lock immediately after the write.
  5. signal(full) – announce that one more item is ready. A consumer blocked in wait(full) wakes on this.

The steps above are the producer. The consumer is the mirror image: wait(full), wait(mutex), remove the item, signal(mutex), signal(empty).

Two properties make this correct. empty and full make overflow and underflow impossible: a producer cannot pass wait(empty) when no slot is free, and a consumer cannot pass wait(full) when nothing is there. And the waits are ordered resource first, lock second, so a blocked process never holds the mutex.

The buffer is circular: the producer writes at in, the consumer reads at out, and each index advances as (i + 1) % N. The program prints only what every run agrees on: items come out in the order they went in, the buffer never holds more than N, and it ends empty.

  • Each side signals the semaphore the other waits on: that hand-off is the solution
  • With several producers, the mutex stops two of them writing the same slot
  • The two signals at the end can go in either order
  • Threads interleave differently on every run; the semaphores make every interleaving safe
Implementation

Code in Python, C++ and Java

import threading

N = 3

buffer = []
empty = threading.Semaphore(N)  # free slots a producer may claim
full = threading.Semaphore(0)   # filled slots a consumer may claim
mutex = threading.Lock()        # guards the buffer itself, nothing more

consumed = []
largest = 0


def producer(items):
    global largest
    for item in items:
        empty.acquire()  # claim a slot BEFORE taking the lock
        with mutex:
            buffer.append(item)
            largest = max(largest, len(buffer))
        full.release()


def consumer(count):
    for _ in range(count):
        full.acquire()  # claim an item BEFORE taking the lock
        with mutex:
            consumed.append(buffer.pop(0))
        empty.release()


def main():
    items = list("ABCDEFGHIJ")

    threads = [
        threading.Thread(target=producer, args=(items,)),
        threading.Thread(target=consumer, args=(len(items),)),
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    # The interleaving changes from run to run; these three facts never do.
    print("consumed in order:", " ".join(consumed))
    print(f"buffer never held more than {N} items: {largest <= N}")
    print(f"final buffer size: {len(buffer)}")


if __name__ == "__main__":
    main()
#include <algorithm>
#include <iostream>
#include <mutex>
#include <queue>
#include <semaphore>
#include <string>
#include <thread>
#include <vector>
constexpr int N = 3;
std::queue<char> buffer;
std::counting_semaphore<N> emptySlots(N); // free slots
std::counting_semaphore<N> fullSlots(0); // filled slots
std::mutex bufferMutex; // guards the queue only
std::string consumed;
size_t largest = 0;
void producer(const std::string& items) {
    for (char item : items) {
        emptySlots.acquire(); // claim a slot BEFORE locking
        {
            std::lock_guard<std::mutex> lock(bufferMutex);
            buffer.push(item);
            largest = std::max(largest, buffer.size());
        }
        fullSlots.release();
    }
}
void consumer(int count) {
    for (int i = 0; i < count; i++) {
        fullSlots.acquire(); // claim an item BEFORE locking
        {
            std::lock_guard<std::mutex> lock(bufferMutex);
            consumed += buffer.front();
            buffer.pop();
        }
        emptySlots.release();
    }
}
int main() {
    std::string items = "ABCDEFGHIJ";
    std::thread p(producer, items);
    std::thread c(consumer, static_cast<int>(items.size()));
    p.join();
    c.join();
    // The interleaving changes from run to run; these three facts never do.
    std::cout << "consumed in order:";
    for (char ch : consumed) std::cout << ' ' << ch;
    std::cout << "\nbuffer never held more than " << N << " items: "
    << (largest <= N ? "True" : "False") << '\n';
    std::cout << "final buffer size: " << buffer.size() << '\n';
}
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Semaphore;
class Main {
    static final int N = 3;
    static final Queue<Character> buffer = new ArrayDeque<>();
    static final Semaphore empty = new Semaphore(N); // free slots
    static final Semaphore full = new Semaphore(0); // filled slots
    static final Object mutex = new Object(); // guards the queue only
    static final StringBuilder consumed = new StringBuilder();
    static int largest = 0;
    static void producer(String items) throws InterruptedException {
        for (char item : items.toCharArray()) {
            empty.acquire(); // claim a slot BEFORE locking
            synchronized (mutex) {
                buffer.add(item);
                largest = Math.max(largest, buffer.size());
            }
            full.release();
        }
    }
    static void consumer(int count) throws InterruptedException {
        for (int i = 0; i < count; i++) {
            full.acquire(); // claim an item BEFORE locking
            synchronized (mutex) {
                consumed.append(' ').append(buffer.remove());
            }
            empty.release();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        String items = "ABCDEFGHIJ";
        Thread p = new Thread(() -> {
        try {
        producer(items);
        } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        }
        });
        Thread c = new Thread(() -> {
        try {
        consumer(items.length());
        } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        }
        });
        p.start();
        c.start();
        p.join();
        c.join();
        // The interleaving changes from run to run; these three facts never do.
        System.out.println("consumed in order:" + consumed);
        System.out.println("buffer never held more than " + N + " items: "
        + (largest <= N ? "True" : "False"));
        System.out.println("final buffer size: " + buffer.size());
    }
}
Watch it run

Step through it

Running on bounded buffer N = 3, one producer, one consumer

0
1
2
empty3free slots
full0filled slots
mutex1binary lock
produceridle
consumeridle
Nothing has run yet. This is the initial state the solution assumes.
Step 1

the shared buffer and the three semaphores

A bounded buffer holds N = 3 items. empty counts free slots and starts at 3. full counts filled slots and starts at 0. mutex is a binary lock that protects the buffer indices — it does not protect the counts, because the semaphores already do.

Output
1 / 20
4

Why the Order of the Two Waits Decides Everything

Write the producer as wait(mutex) then wait(empty) and the program deadlocks the first time the buffer fills.

The producer takes the mutex, then finds empty = 0 and blocks while holding the mutex. The consumer then calls wait(mutex) to remove an item: and blocks, because the producer owns it. The producer is waiting for the consumer to free a slot; the consumer is waiting for the producer to free the lock.

That is a textbook circular wait, and it is created by two lines in the wrong order. The rule generalises: never block on a resource semaphore while holding a mutual-exclusion lock.

  • Correct: wait(empty) → wait(mutex) → insert → signal(mutex) → signal(full)
  • Broken: wait(mutex) → wait(empty) → deadlock when full
  • The consumer has the same trap: wait(mutex) before wait(full) deadlocks on an empty buffer
5

Solving It with a Monitor

A monitor removes the ordering trap by making mutual exclusion implicit. Only one process is inside the monitor at a time, and a process that must wait calls wait() on a condition variable, which releases the monitor lock atomically.

So the mistake that deadlocks the semaphore version cannot be written: blocking inside a monitor always frees the lock.

The cost is that condition variables carry no count. notFull.wait() remembers nothing, so the check must sit in a while loop — a woken process has to re-test the condition, because another process may have consumed the slot between the signal and the wakeup.

  • Monitor lock is released automatically on wait
  • Conditions have no memory, so always loop, never if
  • Java's wait/notify and pthread condition variables are this model