Lesson 9 · Synchronization and deadlocks

Sleeping Barber Problem

One barber, one barber chair and a few waiting chairs. The barber must sleep when no one is there and wake when someone arrives, without two customers grabbing one chair or a wake-up getting lost.

Sleeping Barber Problem concept diagramTwo swim lanes. Customer: lock the mutex, check for a free chair, sit and signal customers, then wait on barberReady and get a haircut; with no chair, unlock and leave. Barber: wait on customers, take the next customer and signal barberReady, cut hair, and loop.barbercustomerarrivelock(mutex)waiting < CHAIRS ?waiting++signal(customers)unlock(mutex)wait(barberReady)get haircut, leaveyesno chair:unlock(mutex), leavenostarts asleep:customers = 0wait(customers)sleeps while it is 0waiting−− under the locksignal(barberReady)cut hairwakescallsblue: a signal on one side unblocks a wait on the other
1

The Setup: One Barber, N Chairs

  1. One barber – serves one customer at a time in the barber chair.
  2. N waiting chairs – customers who arrive while the barber is busy sit and wait.
  3. Barber sleeps – when no customer is waiting, the barber sleeps in the chair.
  4. Customer wakes the barber – an arriving customer who finds the barber asleep wakes the barber.
  5. Customer leaves – an arriving customer who finds every waiting chair taken leaves at once.

The sleeping barber problem is a classic synchronization exercise posed by Edsger Dijkstra in 1965. It models a server (the barber) and clients (customers) sharing a bounded waiting queue (the chairs).

The rules sound trivial. The difficulty is that the barber and each customer are separate processes running concurrently, and every rule involves one of them reading shared state and acting on it. If another process changes that state between the read and the action, the rules break.

  • A full room means a rejected customer, not a longer queue
  • Sleeping means blocking on a semaphore, not looping to check the room
2

Why a Naive Solution Fails

Suppose the barber checks the waiting room, sees it empty, and decides to sleep. Before the barber actually blocks, a customer arrives, sees the barber is 'awake' (not yet asleep) and sits down to wait. The barber then sleeps. Now the barber waits for a customer and the customer waits for the barber, forever. This is the lost wakeup problem.

A second race hits the chairs. Two customers arrive together, both read 'one chair free', and both sit down. The room now holds N + 1 people, and the count of waiting customers is wrong from then on.

Both failures are race conditions: the result depends on the exact interleaving. The fix is to make each check-then-act sequence atomic, and to make wake-ups impossible to lose, which is what a semaphore's stored count does.

  • Lost wakeup: fixed by a counting semaphore, which stores a signal nobody is waiting for
  • Double-booked chair: fixed by a mutex around "check waiting, then increment it"
3

The Semaphore Solution

  1. customers – counting semaphore, initial 0. The number of customers waiting; the barber sleeps on it.
  2. barberReady – semaphore, initial 0. The barber signals it to call the next customer to the chair.
  3. mutex – binary semaphore, initial 1. Protects the shared integer waiting.
  4. waiting – integer, initial 0. Customers sitting in the waiting chairs.

Barber, in a loop: wait(customers) (sleep if none), wait(mutex), waiting = waiting − 1, signal(barberReady), signal(mutex), then cut hair.

Customer: wait(mutex). If waiting < CHAIRS: waiting = waiting + 1, signal(customers), signal(mutex), wait(barberReady), then get the haircut. Otherwise signal(mutex) and leave.

The hero diagram lays the two procedures side by side. The customer's signal(customers) releases the barber's wait(customers), and the barber's signal(barberReady) releases the customer's wait(barberReady). Because customers is a counting semaphore, a customer who arrives while the barber is busy leaves a count behind, so the barber never sleeps while someone is waiting.

Note that the customer releases the mutex before waiting on barberReady. Holding the mutex while blocked would stop the barber from ever reaching the chairs, a deadlock.

  • A rejected customer must unlock the mutex before leaving, or the shop freezes
  • Never block while holding the mutex
Key reference

Terms, operations, and practical uses

Semaphores and their initial values

  • customers = 0Counts waiting customers; the barber sleeps on it.
  • barberReady = 0The barber signals it to call one customer.
  • mutex = 1Guards the shared counter waiting.
  • waiting = 0A plain integer, read and written only under the mutex.

Correctness points

  • No lost wake-upsignal(customers) is counted even if the barber is not waiting yet.
  • No overbookingThe chair check and increment happen under one mutex.
  • No deadlockNo one blocks on a semaphore while holding the mutex.
  • Possible starvationPlain semaphores do not guarantee FIFO wake-up order.
Implementation

Code in Python, C++ and Java

import threading
import time

CHAIRS = 3
CUSTOMERS = 6
ARRIVAL_GAP = 0.030  # seconds between arrivals
HAIRCUT = 0.250  # seconds per haircut

customers = threading.Semaphore(0)  # customers waiting; the barber sleeps on it
barber_ready = threading.Semaphore(0)  # the barber signals "next, please"
mutex = threading.Lock()  # protects `waiting`
waiting = 0
served, turned_away = [], []


def barber():
    global waiting
    while True:
        customers.acquire()  # sleep until a customer arrives
        with mutex:
            if waiting == 0:  # woken only to close the shop
                return
            waiting -= 1
            barber_ready.release()  # call the next customer to the chair
        time.sleep(HAIRCUT)


def customer(name):
    global waiting
    with mutex:
        if waiting == CHAIRS:
            turned_away.append(name)
            print(f"{name} leaves: all {CHAIRS} chairs taken")
            return
        waiting += 1
        print(f"{name} sits down ({waiting} waiting)")
        customers.release()  # wake the barber if the barber is asleep
    barber_ready.acquire()  # wait to be called
    with mutex:
        served.append(name)


shop = threading.Thread(target=barber)
shop.start()
people = []
for i in range(1, CUSTOMERS + 1):
    t = threading.Thread(target=customer, args=(f"C{i}",))
    people.append(t)
    t.start()
    time.sleep(ARRIVAL_GAP)
for t in people:
    t.join()

customers.release()  # one last wake-up so the barber can close
shop.join()
# Semaphores do not promise FIFO wake-ups, so sort before printing.
print(f"served {len(served)}: {', '.join(sorted(served))}")
print(f"turned away {len(turned_away)}: {', '.join(turned_away)}")
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <semaphore>
#include <string>
#include <thread>
#include <vector>
using namespace std;
using namespace std::chrono_literals;

const int CHAIRS = 3, CUSTOMERS = 6;
const auto ARRIVAL_GAP = 30ms, HAIRCUT = 250ms;

counting_semaphore<CUSTOMERS> customers(0);  // customers waiting; the barber sleeps on it
binary_semaphore barberReady(0);             // the barber signals "next, please"
mutex seats;                                 // protects `waiting` and the logs
int waiting = 0;
vector<string> served, turnedAway;

void barber() {
    while (true) {
        customers.acquire();  // sleep until a customer arrives
        {
            lock_guard<mutex> lock(seats);
            if (waiting == 0) return;  // woken only to close the shop
            waiting--;
            barberReady.release();  // call the next customer to the chair
        }
        this_thread::sleep_for(HAIRCUT);
    }
}

void customer(const string& name) {
    {
        lock_guard<mutex> lock(seats);
        if (waiting == CHAIRS) {
            turnedAway.push_back(name);
            cout << name << " leaves: all " << CHAIRS << " chairs taken\n";
            return;
        }
        waiting++;
        cout << name << " sits down (" << waiting << " waiting)\n";
        customers.release();  // wake the barber if the barber is asleep
    }
    barberReady.acquire();  // wait to be called
    lock_guard<mutex> lock(seats);
    served.push_back(name);
}

void report(const string& label, vector<string> names) {
    sort(names.begin(), names.end());  // semaphores do not promise FIFO wake-ups
    cout << label << " " << names.size() << ":";
    for (size_t i = 0; i < names.size(); i++) cout << (i ? ", " : " ") << names[i];
    cout << "\n";
}

int main() {
    thread shop(barber);
    vector<thread> people;
    for (int i = 1; i <= CUSTOMERS; i++) {
        people.emplace_back(customer, "C" + to_string(i));
        this_thread::sleep_for(ARRIVAL_GAP);
    }
    for (thread& t : people) t.join();

    customers.release();  // one last wake-up so the barber can close
    shop.join();
    report("served", served);
    report("turned away", turnedAway);
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class Main {
    static final int CHAIRS = 3, CUSTOMERS = 6;
    static final long ARRIVAL_GAP = 30, HAIRCUT = 250; // milliseconds

    static final Semaphore customers = new Semaphore(0); // customers waiting; the barber sleeps on it
    static final Semaphore barberReady = new Semaphore(0); // the barber signals "next, please"
    static final Object seats = new Object(); // protects `waiting` and the logs
    static int waiting = 0;
    static final List<String> served = new ArrayList<>(), turnedAway = new ArrayList<>();

    static void barber() {
        try {
            while (true) {
                customers.acquire(); // sleep until a customer arrives
                synchronized (seats) {
                    if (waiting == 0) return; // woken only to close the shop
                    waiting--;
                    barberReady.release(); // call the next customer to the chair
                }
                Thread.sleep(HAIRCUT);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    static void customer(String name) {
        synchronized (seats) {
            if (waiting == CHAIRS) {
                turnedAway.add(name);
                System.out.println(name + " leaves: all " + CHAIRS + " chairs taken");
                return;
            }
            waiting++;
            System.out.println(name + " sits down (" + waiting + " waiting)");
            customers.release(); // wake the barber if the barber is asleep
        }
        barberReady.acquireUninterruptibly(); // wait to be called
        synchronized (seats) {
            served.add(name);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread shop = new Thread(Main::barber);
        shop.start();
        List<Thread> people = new ArrayList<>();
        for (int i = 1; i <= CUSTOMERS; i++) {
            String name = "C" + i;
            Thread t = new Thread(() -> customer(name));
            people.add(t);
            t.start();
            Thread.sleep(ARRIVAL_GAP);
        }
        for (Thread t : people) t.join();

        customers.release(); // one last wake-up so the barber can close
        shop.join();
        served.sort(null); // semaphores do not promise FIFO wake-ups
        System.out.println("served " + served.size() + ": " + String.join(", ", served));
        System.out.println("turned away " + turnedAway.size() + ": " + String.join(", ", turnedAway));
    }
}
Watch it run

Step through it

Running on arrivals C1…C6, C5 arrives while all 3 chairs are taken

waiting room · 3 chairsbarber chairBasleepdoorwait(customers) blockscustomers (sem)0barberReady (sem)0mutexfreewaiting0served—turned away—
Step 1

The shop opens: the barber sleeps

No customers yet, so the barber calls wait(customers). The semaphore is 0, so the barber blocks. That block is the 'sleep': the thread uses no CPU until someone signals.

Output
1 / 14
4

A Timeline With Two Chairs

Trace the semaphore solution minute by minute, tracking waiting and who is in the chair. The barber cuts C1 from 0 to 4, then C2, C3, C5 and C6 back to back, four minutes each.

  • Waiting chairs – 2.
  • Haircut – 4 minutes each.
  • Arrivals – C1 at 0, C2 at 1, C3 at 2, C4 at 3, C5 at 5, C6 at 9.

The key moment is minute 3. C2 and C3 hold both chairs and C1 is still in the barber chair, so C4 finds waiting == 2 and leaves. At minute 5 a chair has just opened, because C2 moved to the barber at minute 4, so C5 is seated. Nobody else is turned away, and the barber works without a break from 0 to 20, then sleeps.

arrivebarberC1C2C3C4C5C6C4: 2 chairs full, leavesC1C2C3C5C6sleeps02468101214161820minutes · each haircut takes 4 · 2 waiting chairs
  • Served: C1, C2, C3, C5, C6. Turned away: C4
  • A customer is rejected only when waiting == CHAIRS at arrival
  • The barber never sleeps while waiting > 0
  • Final state: customers = 0, waiting = 0, barber asleep
5

Starvation, Fairness and Variants

The basic solution has no deadlock: every wait is matched by a signal from the other side, and nobody blocks while holding the mutex. It can still be unfair. A plain semaphore does not promise to wake waiters in arrival order, so on barberReady a later customer may be called before an earlier one. With a steady stream of arrivals, an unlucky customer can starve.

The fix is a FIFO queue: each customer waits on a private semaphore placed in a queue, and the barber signals the one at the front. Many real semaphore and lock implementations offer a fair mode that does this internally.

Common variants extend the model: multiple barbers (initialise a barber pool and let each loop on customers), customers who wait outside instead of leaving (an unbounded queue, which trades rejection for unbounded delay), and priority customers, which reintroduce starvation for everyone else.

  • Deadlock-free, but not necessarily starvation-free
  • FIFO fairness needs a queue or a fair semaphore
  • Multiple barbers: several threads loop on the same semaphore
  • Rejecting at a full room bounds both memory and waiting time
6

Where the Pattern Shows Up

Strip away the barbershop and the problem is a bounded queue with rejection served by a worker pool. A web server's accept backlog, a thread pool with a bounded task queue, and a call centre with limited hold slots all follow it: idle workers block instead of polling, a full queue rejects new work, and the counters that decide both must be updated atomically.

It sits between the producer-consumer problem, where a full buffer blocks the producer instead of rejecting it, and the readers-writers problem in the family of classic exercises. The same toolkit solves all three; see mutexes, semaphores and monitors.

For an exam answer, give the problem statement, name the two races, list the semaphores with their initial values, write the barber and customer pseudocode, and argue briefly why there is no deadlock and no lost wake-up.

  • Same shape as a bounded thread-pool queue
  • Idle server blocks; full queue rejects
  • Producer-consumer blocks instead of rejecting
  • Exam answer: statement, races, semaphores, pseudocode, argument