Skip to content

Dining Philosophers

There are some variants of this problem. One of them reads:

“There are five philosophers sitting at a round table who do nothing but think and eat. Between each philosopher there is a single fork. In order to eat, a philosopher must have both forks.”

This problem is used to discuss multiprocess synchronization problems, like deadlocks and starvation. You get these problems if you put some restrictions on the way a philosopher grabs for a fork, for instance, first on the right and then waits for the fork on the left. But in this article we do not want to model synchronization problems — so we realize the working system where a philosopher starts eating if both forks at his sides are free. As this example has been invented as a Christmas gift, studying starvation would not be a proper topic.

We based some of the wording on an article we contributed to, which discusses state machines and multithreading in .NET. You might find it interesting to compare the effort involved in coding these systems manually versus using a ready-made execution framework like StateWORKS.

A philosopher’s behavior is simulated by a state machine represented by the following state transition diagram:

philosophers-st-diagram

The eating time and thinking time are defined by separate timers. The forks are represented by XDA objects.

To simulate the problem, we need 5 state machines, one for each philosopher. The state machines are not a system of state machines; they are just 5 separate state machines. The dependencies among philosophers (state machines) come into being as they use common forks (the left fork of one philosopher is the right fork of his neighbor).

For details take a look at the specification details automatically generated by StateWORKS.

You may test the system using our development tools and run DiningPh.swd using SWLab and monitor the system using SWMon. The system uses digital outputs to indicate thinking philosophers: if a DO is on, the philosopher thinks; otherwise, he eats or is hungry. In SWMon, you may change the timeout values for thinking and eating, but we can assure you that for any combination of timeout values, no philosopher will starve (well, assuming that you do not use very large values).