# The Dining Philosophers Problem

• Canonical concurrency problem used to illustrate the threat of deadlock.
• Five philosophers sit around a circular table, each in front of a big plate of spaghetti.
• A single fork is placed in between adjacently seated philosophers.
• Every day, each philosopher comes to the table to think, eat, think, eat, think, and eat.
That's three square meals of spaghetti after three extended think sessions.
• Each philosopher keeps to himself as he thinks. Sometime he thinks for a long time, and sometimes he thinks for only a short time.
• After each philosopher has thought for a while, he proceeds to eat one of his three daily meals. In order to eat, he must grab hold of two forksâ€”the one to his left, and the one to his right. Once that has happened, he chows down on spaghetti to nourish his big, philosophizing brain. When he's full, he puts down the forks in the same order he picked them up and returns to thinking for a while.

# The Dining Philosophers (continued)

• Here's the core of a C++ program simulating what we just described (click here for full program):

``````static const unsigned int kNumPhilosophers = 5; // must be 2 or greater
static const unsigned int kNumForks = kNumPhilosophers;
static const unsigned int kNumMeals = 3;

static mutex forks[kNumForks]; // forks modeled as mutexes

static void think(unsigned int id) {
cout << oslock << id << " starts thinking." << endl << osunlock;
sleep_for(getThinkTime());
cout << oslock << id << " all done thinking. " << endl << osunlock;
}

static void eat(unsigned int id) {
unsigned int left = id;
unsigned int right = (id + 1) % kNumForks;
forks[left].lock();
forks[right].lock();
cout << oslock << id << " starts eating om nom nom nom." << endl << osunlock;
sleep_for(getEatTime());
cout << oslock << id << " all done eating." << endl << osunlock;
forks[left].unlock();
forks[right].unlock();
}

static void philosopher(unsigned int id) {
for (unsigned int i = 0; i < kNumMeals; i++) {
think(id);
eat(id);
}
}

int main(int argc, const char *argv[]) {
for (unsigned int i = 0; i < kNumPhilosophers; i++)