1 # define N 5
2 # define LEFT (i + N - 1) % N
3 # define RIGHT (i + 1) % N
4 # define THINKING 0
5 # define HUNGRY 1
6 # define EATING 2
7 typedef int semaphore;
8 int state[N];
9 semaphore mutex = 1;
10 semaphore s[N];
11
12 void philosopher(int i){
13 while(TRUE){
14 think();
15 take_two(i);
16 eat();
17 put_now(i);
18 }
19 }
20
21 void take_two(int i){
22 down(&mutex);
23 state[i] = HUNGRY;
24 test(i);
25 up(&mutex);
26 down(&s[i]);
27 }
28
29 void put_two(i){
30 down(&mutex);
31 state[i] = THINKING;
32 test(LEFT);
33 test(RIGHT);
34 up(&mutex);
35 }
36
37 void test(i){ //尝试拿起两把筷子
38 if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
39 state[i] = EATING;
40 up(&s[i]);
41 }
42 }