Download pseudo source code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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