The dining
philosophers problem is explained in chapter VI of your book, page 270. In the
first solution proposed, a deadlock can occur. You can observe this deadlock by
executing the implementation.
Example:
- Philos.java, implementation of the
system composed of 5 philosophers and 5 chopsticks.
- Philosopher.java, implementation
of a philosopher and its behavior.
- Chopstick.java, implementation
of a chopstick with its semaphore.
- deadlock.txt, example of a
deadlock.
As we can see, the problem is
due to the fact that all philosophers can take the left chopstick at the same
time. Thus, they will all wait for the other chopsticks forever. A possible
solution is to restrict the number of philosophers sitting at the table.
This can be implemented by modeling a dining room. Philosophers must enter the dining room to eat and must leave it once they finished eating. By restricting to 4 the number of philosophers in the dining room, we insure that at least one will be able to eat, and so, will release its chopsticks.
The implementation of the solution follows:
- Philos.java, implementation of
the system composed of 5 philosophers and 5 chopsticks.
- Philosopher.java,
implementation of a philosopher and its behavior.
- Chopstick.java, implementation
of a chopstick with its semaphore.
- DiningRoom.java,
implementation of the class Dining Room modeling a dining room and its
semaphore.
Moreover, this
solution insures that no starvation will occur since a philosopher getting out
of the room will not be able to re-enter it directly if there is another
philosopher already waiting at the door.