Download pseudo source code

procedure main(argc, argv[]):
  shared chopsticks[] := create_semaphores(5, 1)

  for id := 0 to 5 do
    create_thread(philosopher, id)
  end for
end procedure

procedure philosopher(id):
  while true do
    think()
    if id % 2 = 0 then
      get_right_chopstick(id)
      get_left_chopstick(id)
    else
      get_left_chopstick(id)
      get_right_chopstick(id)
    end if
    eat()
    put_left_chopstick(id)
    put_right_chopstick(id)
  end while
end procedure

procedure get_left_chopstick(id):
  wait(chopsticks[(id + 1) mod 5])
end procedure

procedure get_right_chopstick(id):
  wait(chopsticks[id])
end procedure

procedure put_left_chopstick(id):
  signal(chopsticks[(id + 1) mod 5])
end procedure

procedure put_right_chopstick(id):
  signal(chopsticks[id])
end procedure