Dining Philosophers & Sleeping Barber Problems in OS Explained Simply

Operating System Chapter 10 · Classical Concurrency Casebook
Dining Philosophers & Sleeping Barber Problems in OS Explained Simply

Dining Philosophers and Sleeping Barber are classical Operating System synchronization problems used to explain resource sharing, blocking, deadlock, starvation and semaphore coordination. In the Dining Philosophers problem, five philosophers compete for five forks and each philosopher needs two forks to eat. A careless solution can deadlock if everyone holds one fork and waits for the other. In the Sleeping Barber problem, one barber, one barber chair and a limited waiting room must coordinate arriving customers. If no customer exists, the barber sleeps; if the waiting room is full, a new customer leaves. This chapter explains both problems from the story first, then builds the semaphore logic, solved traces and deadlock-free approaches step by step.

Dining Philosophers Sleeping Barber Deadlock Starvation Semaphores Classical synchronization
Two classic case files

Why Are These Problems So Important in Operating Systems?

Dining Philosophers & Sleeping Barber Problems in OS Explained Simply

Both problems are small stories that represent real synchronization situations. They help students see why processes cannot simply grab shared resources whenever they want.

Dining Philosophers

Focuses on multiple processes competing for multiple resources and shows how circular waiting can cause deadlock.

Sleeping Barber

Focuses on coordination between a service process and arriving client processes when waiting space is limited.

These problems make much more sense if you already understand Semaphores in OS and Critical Section & Mutual Exclusion.

CASE FILE A: Dining Philosophers Five philosophers, five forks, and one dangerous circular wait.

What Is the Dining Philosophers Problem?

The Dining Philosophers Problem has five philosophers sitting around a circular table with one fork between each pair. A philosopher must hold both the left and right fork to eat.

Each philosopher repeatedly does two things: thinks and eats. Thinking needs no fork. Eating needs two forks.

DINING TABLE
5 PHILOSOPHERS
5 FORKS
P0needs F4 + F0
P1needs F0 + F1
P2needs F1 + F2
P3needs F2 + F3
P4needs F3 + F4
F0between P0 and P1
F1between P1 and P2
F2between P2 and P3
F3between P3 and P4
F4between P4 and P0
The dangerous naive solution

How Does Deadlock Happen?

Imagine every philosopher follows this rule:

pick left fork -> pick right fork -> eat -> release both

Now suppose all five philosophers pick up their left fork at almost the same time.

P0 holds F4
waits F0
P1 holds F0
waits F1
P2 holds F1
waits F2
P3 holds F2
waits F3
P4 holds F3
waits F4

Every philosopher holds one fork and waits for another fork held by the next philosopher. Nobody can move forward. This is deadlock.

Hold one + wait for next + circular chain = deadlock
Connect it to deadlock theory

Which Deadlock Conditions Appear Here?

Mutual ExclusionOne fork can be used by only one philosopher at a time.
Hold and WaitEach philosopher can hold one fork while waiting for another.
No PreemptionA fork is not forcibly taken away from a philosopher.
Circular WaitP0 waits for P1's fork, P1 waits for P2's, and so on in a cycle.

The Dining Philosophers problem is therefore a perfect visual example of the four classic deadlock conditions.

Semaphore representation

How Can Forks Be Represented With Semaphores?

Each fork can be represented as a binary semaphore initialized to 1.

fork[0] = fork[1] = fork[2] = fork[3] = fork[4] = 1

A philosopher waits on the two required forks before eating and signals them after eating.

Naive Philosopher Pi

while (true) {
    think();

    wait(left_fork);
    wait(right_fork);

    eat();

    signal(right_fork);
    signal(left_fork);
}

Main Problem

If every philosopher
takes one fork first,
all five can hold
one resource and wait
forever for the second.
Deadlock-free approaches

How Can We Prevent Dining Philosopher Deadlock?

1. Allow at most four philosophers to try

Use another semaphore initialized to 4. With only four philosophers competing for forks, the complete circular wait can be broken.

2. Pick forks in a global order

Always request the lower-numbered fork first and then the higher-numbered fork. This removes circular resource ordering.

3. Make one philosopher reverse order

For example, four philosophers pick left then right while one philosopher picks right then left. This breaks the perfect cycle.

4. Use a monitor/state-based solution

A philosopher eats only when both neighbors are not eating, while condition variables manage waiting safely.

Solved approach

Solution Using a “Room” Semaphore of 4

Add:

room = 4

Each philosopher must enter the room before trying to pick forks.

Deadlock-Free Idea

while (true) {
    think();

    wait(room);

    wait(left_fork);
    wait(right_fork);

    eat();

    signal(right_fork);
    signal(left_fork);

    signal(room);
}

Why it helps

Only 4 philosophers
can compete for 5 forks.

At least one philosopher
can eventually obtain
two forks and eat.

The full 5-process
circular wait is broken.
Dining trace

Simple Dining Philosophers Execution Trace

P0 enters roomroom decreases from 4 to 3.
P1, P2 and P3 also enterroom becomes 0. P4 must wait outside.
The four philosophers compete for five forksBecause one philosopher is absent from the competition, the complete circular chain of five cannot form.
One philosopher gets both forksThat philosopher eats and then releases the forks.
Released forks let another philosopher proceedProgress continues instead of all five waiting forever.
When a philosopher leaves, signal(room)P4 can then join the competition.
Deadlock vs starvation

Can Dining Philosophers Still Have Starvation?

Yes. A deadlock-free solution is not automatically starvation-free.

A philosopher may repeatedly lose access to forks while neighbors keep getting them first. Fair queueing or a monitor design may be needed to provide stronger fairness.

Deadlock

No philosopher in the deadlocked set can move forward.

Starvation

The system keeps making progress, but one unlucky philosopher waits for an extremely long time.

CASE FILE B: Sleeping Barber One barber, one barber chair, limited waiting chairs, and customers arriving at random times.

What Is the Sleeping Barber Problem?

The Sleeping Barber Problem models a barber shop with one barber, one barber chair and a limited number of waiting chairs. If no customer is present, the barber sleeps. If a customer arrives and the barber is sleeping, the customer wakes the barber. If the barber is busy, the customer waits if a chair is free. If all waiting chairs are occupied, the customer leaves.

BARBER
sleeping or cutting
Chair 1
Customer
Chair 2
Customer
Chair 3
Empty
Chair 4
Empty
SHOP DOOR
new customers arrive
What must be synchronized?

Main Sleeping Barber Synchronization Rules

Barber sleeps when no customer existsThe barber should not waste CPU-like work when there is nobody to serve.
Customer wakes barber when neededAn arriving customer signals that work is available.
Waiting chairs are limitedA customer can wait only if a free chair exists.
Full waiting room means leaveIf every waiting chair is occupied, the new customer cannot stay.
Waiting count is shared dataBarber and customers must not update the count unsafely.
One customer is served at a timeThere is only one barber chair in the classic problem.
Semaphore control desk

Which Semaphores Are Used in the Sleeping Barber Solution?

customers Counts waiting customers. The barber waits here when no customer exists.
barbers Signals that the barber is ready to serve one customer.
mutex Protects the shared waiting-customer count and chair decisions.

Typical initialization is:

customers = 0 · barbers = 0 · mutex = 1 · waiting = 0
Barber logic

Sleeping Barber Semaphore Solution: Barber Code

Barber

while (true) {
    wait(customers);

    wait(mutex);
    waiting = waiting - 1;
    signal(barbers);
    signal(mutex);

    cut_hair();
}

Meaning

sleep if no customer
lock waiting count
take one waiting customer
tell customer barber is ready
unlock shared count
cut hair
Customer logic

Sleeping Barber Semaphore Solution: Customer Code

Customer

wait(mutex);

if (waiting < chairs) {
    waiting = waiting + 1;

    signal(customers);
    signal(mutex);

    wait(barbers);
    get_haircut();
}
else {
    signal(mutex);
    leave_shop();
}

Meaning

lock waiting count
check free chair

if chair exists:
    join queue
    wake/notify barber
    unlock
    wait for barber

else:
    unlock
    leave shop
Barber trace

Sleeping Barber Example With 3 Waiting Chairs

Assume the barber is sleeping and all three waiting chairs are empty.

Customer C1 arrivesC1 locks mutex, sees a free chair, increments waiting to 1 and signals customers.
Barber wakeswait(customers) succeeds because a customer exists.
Barber locks mutexBarber decreases waiting from 1 to 0 and signals barbers.
C1 gets the barber signalC1 moves from waiting to being served.
C2 and C3 arrive while barber is busyThey can occupy waiting chairs if space exists.
A fourth waiting customer finds all chairs fullThat customer releases mutex and leaves the shop.
Why mutex matters

Why Is mutex Needed in the Barber Problem?

The variable waiting is shared. Many customers can arrive while the barber is also changing the number of waiting customers.

mutex protects the check-and-update of the waiting count so two customers do not both claim the same last chair.

Without mutual exclusion, two customers could read the same old waiting value and both believe that one free chair exists.

What each semaphore prevents

customers, barbers and mutex: Different Jobs

Semaphore / VariableMain PurposeWhat Goes Wrong Without It?
customersCounts/announces waiting customersBarber would not know when work exists
barbersSignals barber readiness to a customerCustomer may not coordinate correctly with service
mutexProtects waiting count and chair decisionsRace conditions on waiting-room state
waitingTracks occupied waiting chairsCannot know whether new customer can stay
chairsMaximum waiting-room capacityNo bounded waiting-room rule
Interactive case explorer

What Happens in These Classical Scenarios?

Dining Philosophers: Naive Deadlock

P0 holds F4, waits F0 P1 holds F0, waits F1 P2 holds F1, waits F2 P3 holds F2, waits F3 P4 holds F3, waits F4 Every philosopher holds one fork and waits for another fork. No one can proceed.

Diagnosis

Deadlock A circular wait exists: each philosopher holds one fork and waits for the next fork in the cycle.
CIRCULAR WAIT FORMED
Compare both case files

Dining Philosophers vs Sleeping Barber

PointDining PhilosophersSleeping Barber
Main ideaProcesses compete for multiple resourcesService process coordinates with arriving clients
Main resourceForksBarber chair and waiting chairs
Main riskDeadlock and starvationRace conditions, lost coordination, full waiting room
Common semaphore useFork semaphores plus optional room/monitor logiccustomers, barbers and mutex
Capacity issueLimited forksLimited waiting chairs
Teaching focusResource allocation and circular waitBlocking/wakeup and bounded waiting-room coordination
Common mistakes

Common Student Confusions

Dining Philosophers is not only about forksIt represents general processes competing for multiple resources.
Deadlock-free does not always mean starvation-freeA philosopher may still wait too long in an unfair solution.
room = 4 does not replace fork semaphoresIt only limits how many philosophers can compete at once.
Sleeping barber is not just a queue problemIt also needs blocking, wakeup and mutual exclusion.
customers and barbers do different jobsOne counts/announces customers; the other signals barber readiness.
waiting must be protectedIt is shared state accessed by both barber and customers.
Full waiting room means customer leavesThe classic problem does not allow unlimited queue growth.
Semaphore order mattersWrong wait/signal ordering can introduce deadlock or incorrect coordination.
Exam answer strategy

How to Write These Problems in Semester Exams

2 marks

Problem definition

Write the story, shared resources and the main synchronization problem.

5 marks

One classical problem

Add a diagram, semaphore variables and explain how deadlock or waiting is handled.

8-10 marks

Complete answer

Write full semaphore pseudocode, explain every semaphore, add a solved trace and discuss deadlock/starvation or full waiting-room cases.

Fast memory trick

Dining Philosophers = forks + circular wait · Sleeping Barber = customers + chairs + wake/sleep
Quick practice

Practice Questions With Answers

1. What is the Dining Philosophers Problem?

It is a synchronization problem where philosophers compete for shared forks and each philosopher needs two forks to eat.

2. How can deadlock occur in Dining Philosophers?

If every philosopher picks one fork and waits for the second, a circular wait can form and nobody can proceed.

3. How can a room semaphore prevent Dining Philosopher deadlock?

If room is initialized to 4, at most four of five philosophers compete for forks at one time, which breaks the complete five-process circular wait.

4. Can Dining Philosophers have starvation?

Yes. A solution may avoid deadlock but still allow one philosopher to wait for a very long time if access is unfair.

5. What is the Sleeping Barber Problem?

It is a synchronization problem where one barber serves customers, sleeps when no customer exists, and uses a limited waiting room for customers who arrive while the barber is busy.

6. What does the customers semaphore do?

It counts or announces waiting customers and allows the barber to sleep when no customer exists.

7. Why is mutex needed in Sleeping Barber?

mutex protects the shared waiting count and prevents multiple customers from claiming the same free chair through a race condition.

8. What happens when all waiting chairs are full?

A newly arriving customer leaves the shop because no waiting space is available.

9. What are the four deadlock conditions visible in Dining Philosophers?

Mutual exclusion, hold and wait, no preemption and circular wait.

10. Which OS topic connects both problems?

Process synchronization using semaphores, mutual exclusion and correct coordination of shared resources connects both problems.

Casebook recap

One-Minute Revision Board

Dining Philosophers5 philosophers, 5 forks, 2 forks needed to eat.
Naive riskEveryone holds one fork and waits for another.
Deadlock conditionCircular wait among philosophers.
room = 4Limits simultaneous competitors and breaks the full cycle.
Global orderingAnother way to break circular wait.
StarvationCan still happen in an unfair deadlock-free solution.
Sleeping BarberOne barber, one barber chair, limited waiting chairs.
customersCounts/announces waiting customers.
barbersSignals barber readiness.
mutexProtects waiting-room state.
No customerBarber sleeps.
No free chairCustomer leaves.
Frequently asked questions

Frequently Asked Questions

What is the main idea of the Dining Philosophers Problem?

It shows how multiple processes competing for multiple shared resources can create deadlock or starvation if resource acquisition is not coordinated correctly.

Why does the naive Dining Philosophers solution deadlock?

If every philosopher holds one fork and waits for the next fork, a circular wait forms and no philosopher can obtain both forks.

What is one simple deadlock-free Dining Philosophers solution?

Use a semaphore initialized to 4 so at most four of the five philosophers may try to acquire forks at the same time.

What is the Sleeping Barber Problem in simple words?

It models one barber serving arriving customers with a limited waiting room, where the barber sleeps when no customer exists and customers leave when all waiting chairs are full.

Which semaphores are commonly used in Sleeping Barber?

A common solution uses customers to count waiting customers, barbers to signal barber readiness and mutex to protect the shared waiting count.

What is the difference between deadlock and starvation in these problems?

Deadlock means a set of processes cannot make progress, while starvation means the system progresses but one process may wait for an extremely long time.

Next classical synchronization topic

What Should You Learn Next?

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources