I need to check my algorithm of solving the dining philosopher problem if it guarantees that all of the following are satisfied or not:
- No possibility of deadlock.
- No possibility of starvation.
I am using the semaphore on the chopsticks to solve the problem.
Here is my code (the algorithm):
while(true)
{
// He is Hungry
pickup_chopsticks(i);
// He is Eating...
drop_chopsticks(i);
// He is thinking
}
// ...
void pickup_chopsticks(int i)
{
if(i % 2 == 0) /* Even number: Left, then right */
{
semaphore_wait(chopstick[(i+1) % NUM_PHILOSOPHERS]);
semaphore_wait(chopstick[i]);
}
else /* Odd number: Right, then left */
{
semaphore_wait(chopstick[i]);
semaphore_wait(chopstick[(i+1) % NUM_PHILOSOPHERS]);
}
}
void drop_chopsticks(int i)
{
semaphore_signal(chopstick[i]);
semaphore_signal(chopstick[(i+1) % NUM_PHILOSOPHERS]);
}
I am sure there is no possibility of deadlock here, but is it possible to have a starvation problem here? If yes, how can I solve it?