Thursday Code Puzzler: Dining Philosophers
Join the DZone community and get the full member experience.Join For Free
by now you should be familiar with our thursday code puzzler slot. the idea is simple: solve the coding problem as efficiently as you can, in any language or framework that you think is suitable.
note: even though there really is nothing stopping you from finding a solution to this on the internet, try to keep honest, and come up with your own answer. it's all about the participation!
the dining philosophers problem
this week's problem is another classic computer science puzzle, which deals with concurrency and trying to avoid deadlocks. the problem statement is as follows (taken from wikipedia)
five silent philosophers sit at a table around a bowl of spaghetti. a fork is placed between each pair of adjacent philosophers.each philosopher must alternately think and eat. eating is not limited by the amount of spaghetti left: assume an infinite supply.
however, a philosopher can only eat while holding both the fork to the left and the fork to the right (an alternative problem formulation uses rice and chopsticks instead of spaghetti and forks).
each philosopher can pick up an adjacent fork, when available, and put it down, when holding it. these are separate actions: forks must be picked up and put down one by one.
the problem is how to design a discipline of behavior (a concurrent algorithm) such that each philosopher won't starve, i.e. can forever continue to alternate between eating and thinking.
try to make the solution as efficient as possible, and if you do get to run it post up your timings, or even better, the big o notation for your solution.
Opinions expressed by DZone contributors are their own.