Dining philosophers problem
In computer science, the dining philosophers problem is an illustrative example of a common computing problem in concurrency. It is a classic multi-process synchronization problem.
In 1965, Edsger Dijkstra used the example of a group of philosophers to solve a synchronization problem. Five philosophers are sitting around a circular table and each has a plate of spaghetti in front of him with a fork at either side (i.e. five philosophers, five plates, and five forks).
Suppose that the life of a philosopher consists of periods of eating and thinking, that each philosopher needs two forks to eat, and that forks are picked up one at a time. After successfully picking up two forks, a philosopher eats for a while and then puts down the forks and thinks. The problem consists in developing an algorithm to avoid starvation and deadlock. Deadlock might occur if each of the five philosophers has one fork and no one can get a second fork. The philosopher a waits for the fork grabbed by philosopher b who is waiting for the fork of philosopher c and so forth, making a circular chain of deadlock. Starvation might also happen independently of deadlock if a philosopher is unable to acquire both forks.
A working solution consists of having the philosophers report their state as hungry, thinking, and eating. A philosopher cannot eat unless he has declared his state as hungry and both of his neighboring philosophers are not eating. The status of the philosophers is kept using a shared data structure (e.g an array). A philosopher may enter the eating state only if both of his neighbors are not in that state. To ensure this, the philosopher obtains a mutual exclusion (mutex) lock and then changes his state from thinking to hungry. After he changes his state, he tries to obtain both forks and will not do so until both of his neighbors have left the eating state. At that point the philosopher changes his state to eating and releases the lock. The philosopher then eats. After the philosopher is done eating, he again obtains a mutex lock, changes his state to thinking and sees, one at a time, if either of his two neighbors are hungry. If at least one is hungry, that philosopher enters the eating state if his other neighbor is not eating, and the cycle continues.
The lack of available forks is an analogy to the locking of scarce resources in real computer programming, a situation known as concurrency. Locking a resource is a common technique to ensure the resource is accessed by only one program or chunk of code at a time. When the resource the program is interested in is already locked by another one, the program waits until it is unlocked. When several resources are involved in locking resources, deadlock might happen, depending on the circumstances. For example, one program needs two files to process. When two such programs lock one file each, both programs wait for the other one to unlock the other file, which will never happen.