</>

1226. The Dining Philosophers

Medium
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Math & Geometry
Time
—
Space
—

Standard Solution (C++)

SummaryFive philosophers sit at a round table, each needing both adjacent forks to eat. The task is to implement `wantsToEat` so that all five philosophers can eat concurrently without deadlock or starvation, given five mutexes (one per fork) numbered 0–4.

Approach
  • Resource-hierarchy (asymmetric ordering): Each philosopher always picks up the lower-numbered fork first. Because one philosopher's "left" fork has a higher index than their "right" (philosopher 4: left=4, right=0), breaking that cycle eliminates the circular-wait condition that causes deadlock.
  • Four of the five philosophers pick min(left,right) before max(left,right); philosopher 4 effectively picks fork 0 before fork 4, reversing the naive order and cutting the dependency cycle.
  • No semaphore or additional synchronizer is needed — the ordering alone is sufficient to guarantee progress while remaining simple and efficient.
#include <mutex>
#include <functional>
using namespace std;

class DiningPhilosophers {
    mutex forks[5];   // fork i sits between philosopher i and (i+1)%5

public:
    DiningPhilosophers() {}

    void wantsToEat(int philosopher,
                    function<void()> pickLeftFork,
                    function<void()> pickRightFork,
                    function<void()> eat,
                    function<void()> putLeftFork,
                    function<void()> putRightFork) {
        int left  = philosopher;          // fork index on the left
        int right = (philosopher + 1) % 5;// fork index on the right

        // Always acquire the lower-indexed fork first to break circular wait.
        int first  = min(left, right);
        int second = max(left, right);

        lock_guard<mutex> lg1(forks[first]);
        lock_guard<mutex> lg2(forks[second]);

        // Invoke callbacks in the order the judge expects regardless of
        // which physical fork was picked up first.
        pickLeftFork();
        pickRightFork();
        eat();
        putLeftFork();
        putRightFork();
        // lock_guards release both mutexes on scope exit.
    }
};
Time O(1) per philosopher call (constant number of mutex operations) Space O(1) — five mutexes regardless of input

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <mutex>
#include <semaphore>
#include <functional>

class DiningPhilosophers {
private:
    std::mutex forks[5];
    std::counting_semaphore<4> limit{4};

public:
    DiningPhilosophers() {

    }

    void wantsToEat(int philosopher,
                    function<void()> pickLeftFork,
                    function<void()> pickRightFork,
                    function<void()> eat,
                    function<void()> putLeftFork,
                    function<void()> putRightFork) {
		int left=philosopher;
        int right=(philosopher+1)%5;

        limit.acquire();
        forks[left].lock();
        forks[right].lock();

        pickLeftFork();
        pickRightFork();
        eat();
        putLeftFork();
        putRightFork();

        forks[left].unlock();
        forks[right].unlock();

        limit.release();
    }
};

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern