Dining philosophers

Five philosophers are seated around a table There are 5 single chopstick between each pair of philosophers. When any philosopher wants to eat, they have to acquire both chopsticks from their left and right.

We can think of philosophers as threads. How do we synchronize these 5 threads?

#define N 5
#define Left ((i+N-1) % N)
#define Right ((i+1) % N)

#define THINKING 0
#define HUNGRY 1
#define EATING 2

int state[N];
Semaphore mutex = 1;
Semaphore s[N];

void philosopher(int i) {
  while (True) {
    Think();
    takeChopSticks(i);
    Eat();
    putChopSticks(i);
  }
}
void takeChopSticks(i) {
  wait(mutex);
  state[i] = HUNGRY;
  safeToEat(i);
  signal(mutex);
  wait(s[i]);
}

void safeToEat(i)
{
  if state[i] == HUNGRY && state[LEFT] != EATING && STATE[RIGHT] != EATING {
    state[i] = EATING;
    signal(s[i]);
  }
}

void putChopSticks(i)
{
  wait(mutex);
  state[i] = THINKING
  safeToEat(LEFT);
  safeToEat(RIGHT);
  signal(mutex);
}