The “dining philosophers” is the name commonly given to a theoretical concurrency problem introduced by Edsger Dijkstra, one of the earliest researchers in the field. In this article, I am giving a complete solution (starvation-free and maximally occupied) using the POSIX threading model.
The example is used to show a generic programming technique called shared state inspection that I have used through my career to solve most concurrency problems I have encountered.
I will use Java to write the solution, to emphasise the difference between the base Java threading model, based on Dijkstra original proposal using monitors and semaphores versus the later POSIX model. There’s a translation in C++17 at the end of the article to better appreciate the differences between the two languages.
An arbitrary number of philosophers (let’s say five) are sitting around a table. At any given moment, they may be either thinking or eating rice; but there’s a quirk to the situation. They need two chopsticks to eat the rice, but they only have a number of chopsticks equal to theirs; with 5 philosophers, they will have 5 chopsticks. So, each philosopher needs to gather both the chopsticks to its left and right hand sides before eating, and thus, preventing the guests on both sides to do the same.