Five philosophers sit around a circular table. Between each pair of adjacent philosophers is one chopstick (fork). Each philosopher alternates between thinking and eating. To eat, a philosopher must hold both the left and right chopsticks.
Any solution must ensure:
// One binary semaphore per chopstick
semaphore fork[5] = {1,1,1,1,1};
philosopher(i):
while (true) {
think();
wait(fork[i]); // pick up left
wait(fork[(i+1)%5]); // pick up right
eat();
signal(fork[i]); // put down left
signal(fork[(i+1)%5]); // put down right
}
All five wait(fork[i]) succeed, then each blocks on wait(fork[(i+1)%5]). No one can proceed or release their held fork—circular wait.
Introduce a semaphore room initialized to 4 (N–1):
semaphore room = 4;
semaphore fork[5] = {1,1,1,1,1};
wait(room).