|
The Dining Philosopher's problem exemplifies what is called "deadlock." In the problem,
there are five hungry philosophers, five forks, and one big plate of food. Each
philosopher needs two forks in order to eat. The issue of "deadlock" arises when each
philosopher is hungry for food, picks up a fork, and awaits the second fork to be
put down (which will not happen, because each philosopher is holding a fork). In this
case, the philosophers wait infinitely, and eventually starve. A similar event can
happen in your computer, where a few programs need access to a shared resource.
If the programs wait indefinitely, they can starve, and freeze up. But let's get back
to those philosophers...
My solution? As with any restaurant, the philosophers should be managed by a waiter.
In my program, I set up a dining room, five philosophers, five chopsticks (or forks),
and one waiter to manage the five philosophers. The waiter goes around to each
philosopher, and asks if the philosopher is hungry if he isn't already eating or
preoccupied with thought. If the philosopher is hungry, the food is served to him,
and he can eat with both chopsticks. There will be instances where a philosopher is
waiting for a chopstick to be placed down, however the issue of deadlock will never
happen: because the first philosopher is the only one served food when the program
begins, he can eat with two forks, and when he is finished he places the forks down
so philosopher #2 can eat. My variation also allows for many philosophers to be eating
simultaneously (okay, at most 2), because the waiter serves food, then proceeds to ask
the next philosopher.
|