13
13
#define TIMES 4 /* 吃4次饭 */
14
14
#define SLEEP_TIME 10
15
15
16
+ //-----------------philosopher problem using monitor ------------
17
+ /*PSEUDO CODE :philosopher problem using semaphore
18
+ system DINING_PHILOSOPHERS
19
+
20
+ VAR
21
+ me: semaphore, initially 1; # for mutual exclusion
22
+ s[5]: semaphore s[5], initially 0; # for synchronization
23
+ pflag[5]: {THINK, HUNGRY, EAT}, initially THINK; # philosopher flag
24
+
25
+ # As before, each philosopher is an endless cycle of thinking and eating.
26
+
27
+ procedure philosopher(i)
28
+ {
29
+ while TRUE do
30
+ {
31
+ THINKING;
32
+ take_chopsticks(i);
33
+ EATING;
34
+ drop_chopsticks(i);
35
+ }
36
+ }
37
+
38
+ # The take_chopsticks procedure involves checking the status of neighboring
39
+ # philosophers and then declaring one's own intention to eat. This is a two-phase
40
+ # protocol; first declaring the status HUNGRY, then going on to EAT.
41
+
42
+ procedure take_chopsticks(i)
43
+ {
44
+ DOWN(me); # critical section
45
+ pflag[i] := HUNGRY;
46
+ test[i];
47
+ UP(me); # end critical section
48
+ DOWN(s[i]) # Eat if enabled
49
+ }
50
+
51
+ void test(i) # Let phil[i] eat, if waiting
52
+ {
53
+ if ( pflag[i] == HUNGRY
54
+ && pflag[i-1] != EAT
55
+ && pflag[i+1] != EAT)
56
+ then
57
+ {
58
+ pflag[i] := EAT;
59
+ UP(s[i])
60
+ }
61
+ }
62
+
63
+
64
+ # Once a philosopher finishes eating, all that remains is to relinquish the
65
+ # resources---its two chopsticks---and thereby release waiting neighbors.
66
+
67
+ void drop_chopsticks(int i)
68
+ {
69
+ DOWN(me); # critical section
70
+ test(i-1); # Let phil. on left eat if possible
71
+ test(i+1); # Let phil. on rght eat if possible
72
+ UP(me); # up critical section
73
+ }
74
+
75
+ */
76
+
77
+
16
78
//---------- philosophers problem using semaphore ----------------------
17
79
int state_sema [N ]; /* 记录每个人状态的数组 */
18
80
/* 信号量是一个特殊的整型变量 */
@@ -105,7 +167,7 @@ int philosopher_using_semaphore(void * arg) /* i:哲学家号码,从0到N-1
105
167
106
168
struct proc_struct * philosopher_proc_condvar [N ]; // N philosopher
107
169
int state_condvar [N ]; // the philosopher's state: EATING, HUNGARY, THINKING
108
- monitor_t mt , * mtp = & mt ; // mp is mutex semaphore for monitor's procedures
170
+ monitor_t mt , * mtp = & mt ; // monitor
109
171
110
172
void phi_test_condvar (i ) {
111
173
if (state_condvar [i ]== HUNGRY && state_condvar [LEFT ]!= EATING
@@ -128,7 +190,7 @@ void phi_take_forks_condvar(int i) {
128
190
state_condvar [i ]= HUNGRY ;
129
191
// try to get fork
130
192
phi_test_condvar (i );
131
- while (state_condvar [i ] != EATING ) {
193
+ if (state_condvar [i ] != EATING ) {
132
194
cprintf ("phi_take_forks_condvar: %d didn't get fork and will wait\n" ,i );
133
195
cond_wait (& mtp -> cv [i ]);
134
196
}
0 commit comments