In an alternative solution to the dining philosophers, the
philosophers share the following.
int state[];
semaphore mutex;
semaphore block[];
N is the number of philosophers. Each philosopher has
a unique number between 0 and N-1 and a philosopher's state
state[i] is either THINKING, HUNGRY or EATING.
PHILOSOPHER(int i)
{
think;
P(mutex);
if (state[(i - 1) % N] != EATING && state[(i + 1) % N] != EATING)
{
state[i] = EATING;
V(block[i]);
}
else
{
state[i] = HUNGRY;
}
V(mutex);
P(block[i]);
eat;
P(mutex);
state[i] = THINKING;
if (state[(i - 1) % N] == HUNGRY && state[(i - 2) % N] != EATING)
{
V(block[(i - 1) % N]);
}
if (state[(i + 1) % N] == HUNGRY && state[(i + 2) % N] != EATING)
{
V(block[(i + 1) % N]);
}
V(mutex);
}