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 | procedure main(argc, argv[]):
shared chopsticks[] := create_semaphores(5, 1)
shared quota := create_semaphore(4)
for id := 0 to 5 do
create_thread(philosopher, id)
end for
end procedure
procedure philosopher(id):
while true do
think()
wait(quota)
get_left_chopstick(id)
get_right_chopstick(id)
eat()
put_left_chopstick(id)
put_right_chopstick(id)
signal(quota)
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
|