Lesson 10 · Synchronization and deadlocks

Cigarette Smokers Problem

An agent keeps putting two of three ingredients on a table, and exactly one smoker can use them. The puzzle is waking that smoker, and only that one, without changing the agent.

Cigarette Smokers Problem concept diagramLayers from top to bottom: the agent; three ingredient semaphores; three pushers, one per ingredient; a shared box of flags under a mutex; and three smokers, each waiting on its own semaphore.agentplaces 2 of the 3sem tobaccopusher tobaccowaits on tobaccosmoker with tobaccowaits tobaccoSemsem paperpusher paperwaits on papersmoker with paperwaits paperSemsem matchpusher matchwaits on matchsmoker with matchwaits matchSemmutex + isTobacco, isPaper, isMatchsecond pusher of a pair signals the third smoker
1

The Agent, the Smokers and the Rule

  1. Three smokers – each has an endless supply of exactly one ingredient: tobacco, paper or matches.
  2. One agent – has all three, and repeatedly puts two different ones on the table.
  3. The right smoker – the one holding the third ingredient takes both, rolls, smokes, then tells the agent.
  4. The constraint – the agent's code may not change: it only signals one semaphore per ingredient placed.

The cigarette smokers problem was posed by Suhas Patil in 1971. It is a classic synchronization problem because it is easy to state, easy to solve wrongly, and the wrong solution fails in an instructive way: deadlock.

The agent models an operating system handing out resources, and the smokers model processes that each need a particular combination. The rule that the agent's code is fixed matters: if the agent could simply signal the right smoker directly, there would be no problem. The difficulty is building 'wait for two things at once' out of semaphores that only wait for one.

  • Posed by Patil (1971) as a limit of semaphores
  • Ingredients = resources; smokers = processes; agent = OS
  • Agent code is fixed: signal(ingredient) for each item placed
  • Needed: wake exactly one smoker per round
2

Why the Obvious Solution Deadlocks

The obvious code gives each smoker the two ingredients it lacks and has it wait on both. It is correct only if the right smoker happens to win both semaphores.

  • Smoker with tobacco – wait(paper), then wait(match).
  • Smoker with paper – wait(match), then wait(tobacco).
  • Smoker with match – wait(paper), then wait(tobacco).
  • Agent this round – places paper and match: signal(paper), signal(match).

Step 1. The agent signals paper. Both the tobacco smoker and the match smoker are blocked on wait(paper). The scheduler happens to wake the match smoker, which now holds paper and moves on to wait(tobacco).

Step 2. The agent signals match. The paper smoker is blocked on wait(match) and takes it, then moves on to wait(tobacco).

Step 3. The tobacco smoker, the only one who could smoke, is still blocked on wait(paper), which is gone. Two smokers wait for tobacco, which the agent will not place until a smoker signals agentSem. Nobody smokes, so nobody signals: deadlock.

This satisfies the textbook conditions: each smoker holds one resource and waits for another (hold and wait), nothing can be taken back (no preemption), and the waits close a cycle through the agent (circular wait). See deadlocks.

agentwait(agentSem)smoker with matchholds paper · wait(tobacco)smoker with tobaccowait(paper)smoker with paperholds match · wait(tobacco)needs tobacconeeds a smokerto signal itpaper is held hereneeds tobacconobody smokes, so nobody signals agentSem: every process waits foreverorange = the wait-for cycle between the agent and the match smoker
  • The wrong smokers grabbed paper and match
  • Each holds one ingredient and waits for tobacco
  • The agent waits for a cigarette that cannot happen
  • Hold and wait + no preemption + circular wait = deadlock
3

The Pusher Solution

  1. Pushers – one helper thread per ingredient. Pusher tobacco waits on the tobacco semaphore, and so on.
  2. Shared flags – isTobacco, isPaper, isMatch, all false, protected by one mutex.
  3. First pusher of a pair – finds no other flag set, so it sets its own flag and leaves.
  4. Second pusher of a pair – finds its partner's flag set, clears it, and signals the smoker who lacks both.
  5. Smoker – waits on its own semaphore only, smokes, then signals agentSem.

The standard fix, built on the helper threads David Parnas proposed in 1975, leaves the agent untouched and adds a layer between it and the smokers, as the diagram at the top shows. The pushers convert two ingredient signals into one smoker signal. Because the two pushers of a round meet under the same mutex, whichever runs second always sees the first one's flag.

Pusher tobacco, for example, runs: wait(tobacco); lock; if isPaper, clear it and signal(matchSem); else if isMatch, clear it and signal(paperSem); else set isTobacco; unlock. The other two pushers are the same with the names rotated.

Each smoker now waits on a single semaphore of its own, so there is nothing to hold while waiting, and the deadlock of the naive version cannot form. The tracer below runs three agent rounds through the pushers and shows every flag and semaphore value.

  • Agent unchanged: signal(a), signal(b)
  • Pushers meet at flags under one mutex
  • Second pusher signals the smoker who lacks both
  • Smokers wait on one semaphore each, so no hold-and-wait
Key reference

Terms, operations, and practical uses

Semaphores and shared state

  • agentSem = 1The agent may place ingredients; a smoker signals it after smoking.
  • tobacco, paper, match = 0Signalled by the agent; each is waited on by one pusher.
  • tobaccoSem, paperSem, matchSem = 0Each smoker waits on its own.
  • isTobacco, isPaper, isMatch = falsePusher flags, read and written under one mutex.

Correctness points

  • Exactly one smoker per roundOnly the second pusher of a pair signals, and only one smoker semaphore.
  • No deadlockSmokers never hold one resource while waiting for another.
  • Agent unchangedThe solution uses only the two signals the agent already sends.
Implementation

Code in Python, C++ and Java

import threading

INGREDIENTS = ("tobacco", "paper", "match")
# The agent's choices are fixed here so every run prints the same thing.
ROUNDS = [("paper", "match"), ("tobacco", "match"), ("tobacco", "paper"),
          ("paper", "match"), ("tobacco", "match")]

agent_sem = threading.Semaphore(1)
on_table = {name: threading.Semaphore(0) for name in INGREDIENTS}
smoker_sem = {name: threading.Semaphore(0) for name in INGREDIENTS}
mutex = threading.Lock()
flag = {name: False for name in INGREDIENTS}  # guarded by mutex
smoked = {name: 0 for name in INGREDIENTS}


def pusher(mine):
    others = [name for name in INGREDIENTS if name != mine]
    while True:
        on_table[mine].acquire()
        with mutex:
            partner = next((name for name in others if flag[name]), None)
            if partner is None:
                flag[mine] = True  # first of the pair: leave a note
            else:
                flag[partner] = False  # second: wake the smoker who lacks both
                missing = next(name for name in others if name != partner)
                smoker_sem[missing].release()


def smoker(has):
    while True:
        smoker_sem[has].acquire()
        smoked[has] += 1
        print(f"smoker with {has} rolls and smokes")
        agent_sem.release()


for name in INGREDIENTS:
    threading.Thread(target=pusher, args=(name,), daemon=True).start()
    threading.Thread(target=smoker, args=(name,), daemon=True).start()

for first, second in ROUNDS:
    agent_sem.acquire()
    print(f"agent puts {first} + {second}")
    on_table[first].release()
    on_table[second].release()
agent_sem.acquire()  # wait for the last cigarette

print("cigarettes:", ", ".join(f"{name} {smoked[name]}" for name in INGREDIENTS))
#include <iostream>
#include <mutex>
#include <semaphore>
#include <string>
#include <thread>
#include <utility>
#include <vector>
using namespace std;

enum Item { TOBACCO, PAPER, MATCH };
const string NAMES[] = {"tobacco", "paper", "match"};
// The agent's choices are fixed here so every run prints the same thing.
const vector<pair<Item, Item>> ROUNDS = {
    {PAPER, MATCH}, {TOBACCO, MATCH}, {TOBACCO, PAPER}, {PAPER, MATCH}, {TOBACCO, MATCH}};

binary_semaphore agentSem(1);
binary_semaphore onTable[3] = {binary_semaphore(0), binary_semaphore(0), binary_semaphore(0)};
binary_semaphore smokerSem[3] = {binary_semaphore(0), binary_semaphore(0), binary_semaphore(0)};
mutex tableLock;
bool flag[3] = {false, false, false};  // guarded by tableLock
int smoked[3] = {0, 0, 0};

void pusher(Item mine) {
    while (true) {
        onTable[mine].acquire();
        lock_guard<mutex> lock(tableLock);
        int partner = -1;
        for (int other = 0; other < 3; other++) {
            if (other != mine && flag[other]) partner = other;
        }
        if (partner == -1) {
            flag[mine] = true;  // first of the pair: leave a note
        } else {
            flag[partner] = false;  // second: wake the smoker who lacks both
            int missing = 3 - mine - partner;
            smokerSem[missing].release();
        }
    }
}

void smoker(Item has) {
    while (true) {
        smokerSem[has].acquire();
        smoked[has]++;
        cout << "smoker with " << NAMES[has] << " rolls and smokes\n";
        agentSem.release();
    }
}

int main() {
    for (Item item : {TOBACCO, PAPER, MATCH}) {
        thread(pusher, item).detach();
        thread(smoker, item).detach();
    }

    for (auto [first, second] : ROUNDS) {
        agentSem.acquire();
        cout << "agent puts " << NAMES[first] << " + " << NAMES[second] << "\n";
        onTable[first].release();
        onTable[second].release();
    }
    agentSem.acquire();  // wait for the last cigarette

    cout << "cigarettes: tobacco " << smoked[TOBACCO] << ", paper " << smoked[PAPER]
         << ", match " << smoked[MATCH] << "\n";
}
import java.util.concurrent.Semaphore;

public class Main {
    static final String[] NAMES = {"tobacco", "paper", "match"};
    static final int TOBACCO = 0, PAPER = 1, MATCH = 2;
    // The agent's choices are fixed here so every run prints the same thing.
    static final int[][] ROUNDS = {{PAPER, MATCH}, {TOBACCO, MATCH}, {TOBACCO, PAPER}, {PAPER, MATCH}, {TOBACCO, MATCH}};

    static final Semaphore agentSem = new Semaphore(1);
    static final Semaphore[] onTable = {new Semaphore(0), new Semaphore(0), new Semaphore(0)};
    static final Semaphore[] smokerSem = {new Semaphore(0), new Semaphore(0), new Semaphore(0)};
    static final Object tableLock = new Object();
    static final boolean[] flag = new boolean[3]; // guarded by tableLock
    static final int[] smoked = new int[3];

    static void pusher(int mine) {
        while (true) {
            onTable[mine].acquireUninterruptibly();
            synchronized (tableLock) {
                int partner = -1;
                for (int other = 0; other < 3; other++) {
                    if (other != mine && flag[other]) partner = other;
                }
                if (partner == -1) {
                    flag[mine] = true; // first of the pair: leave a note
                } else {
                    flag[partner] = false; // second: wake the smoker who lacks both
                    int missing = 3 - mine - partner;
                    smokerSem[missing].release();
                }
            }
        }
    }

    static void smoker(int has) {
        while (true) {
            smokerSem[has].acquireUninterruptibly();
            smoked[has]++;
            System.out.println("smoker with " + NAMES[has] + " rolls and smokes");
            agentSem.release();
        }
    }

    static void startDaemon(Runnable body) {
        Thread t = new Thread(body);
        t.setDaemon(true);
        t.start();
    }

    public static void main(String[] args) {
        for (int item = 0; item < 3; item++) {
            int mine = item;
            startDaemon(() -> pusher(mine));
            startDaemon(() -> smoker(mine));
        }

        for (int[] round : ROUNDS) {
            agentSem.acquireUninterruptibly();
            System.out.println("agent puts " + NAMES[round[0]] + " + " + NAMES[round[1]]);
            onTable[round[0]].release();
            onTable[round[1]].release();
        }
        agentSem.acquireUninterruptibly(); // wait for the last cigarette

        System.out.println("cigarettes: tobacco " + smoked[TOBACCO] + ", paper " + smoked[PAPER] + ", match " + smoked[MATCH]);
    }
}
Watch it run

Step through it

Running on agent rounds: paper + match, tobacco + match, tobacco + paper

agenttablepusher TisTobacco = falsepusher PisPaper = falsepusher MisMatch = falseThas tobaccoPhas paperMhas matchinitial stateingredient semaphores (agent → pushers)T · P · M0 · 0 · 0pusher flags (under the mutex)isT · isP · isMF · F · Fsmoker semaphores (pushers → smokers)T · P · M0 · 0 · 0agentSem1agentSem = 1: the agent may placeeverything else starts at 0 / false
Step 1

Three smokers, one agent, three pushers

Each smoker holds an endless supply of one ingredient. The agent puts two different ingredients on the table; the smoker holding the third must take them. Three pusher threads sit between the agent and the smokers and decide who that is.

Output
1 / 13
4

Which Smoker Each Round Wakes

There are only three possible rounds, and in each the pusher that runs second picks the smoker. The table is worth memorising, because an exam answer that lists it proves the solution covers every case.

The order in which the two pushers run does not matter. If pusher paper runs first it sets isPaper and pusher match signals the tobacco smoker; if pusher match runs first it sets isMatch and pusher paper signals the same smoker.

Which smoker the second pusher wakes
Agent placesPushers that wakeSmoker signalled
paper + matchpusher paper, pusher matchsmoker with tobacco
tobacco + matchpusher tobacco, pusher matchsmoker with paper
tobacco + paperpusher tobacco, pusher papersmoker with match
  • The same pusher can wake a different smoker each round: the flag it finds decides
  • Order of the two pushers never changes the outcome
  • Flags are always all false again after a round
  • Exactly one smoker semaphore is signalled per round
5

What the Problem Teaches

Patil used the problem to argue that semaphores were too weak, because the agent-unchanged version seemed impossible without conditionals. Parnas answered that semaphores plus ordinary shared variables and helper threads are enough. Both points survive: plain wait and signal cannot say 'wait until A and B are both available', and the standard workaround is to add state and a thread, or a monitor with a condition to check.

The pattern appears whenever a consumer needs a combination of resources that arrive separately: a join that fires when two inputs are ready, a scheduler that starts a task only when all its inputs exist, or an I/O completion handler waiting for several events. Collect partial arrivals in shared state, and signal only when a complete set exists.

It sits alongside the dining philosophers and sleeping barber problems. The dining philosophers deadlock through a cycle of forks; the smokers deadlock through a wrong assignment of partial resources.

  • Plain semaphores cannot wait on a conjunction
  • Fix: shared state + helper threads, or a monitor
  • Same pattern as a join over several inputs
  • Exam answer: statement, naive deadlock, pushers, which smoker each round wakes