|
|
@ -13,6 +13,68 @@ |
|
|
|
#define TIMES 4 /* 吃4次饭 */ |
|
|
|
#define SLEEP_TIME 10 |
|
|
|
|
|
|
|
//-----------------philosopher problem using monitor ------------ |
|
|
|
/*PSEUDO CODE :philosopher problem using semaphore |
|
|
|
system DINING_PHILOSOPHERS |
|
|
|
|
|
|
|
VAR |
|
|
|
me: semaphore, initially 1; # for mutual exclusion |
|
|
|
s[5]: semaphore s[5], initially 0; # for synchronization |
|
|
|
pflag[5]: {THINK, HUNGRY, EAT}, initially THINK; # philosopher flag |
|
|
|
|
|
|
|
# As before, each philosopher is an endless cycle of thinking and eating. |
|
|
|
|
|
|
|
procedure philosopher(i) |
|
|
|
{ |
|
|
|
while TRUE do |
|
|
|
{ |
|
|
|
THINKING; |
|
|
|
take_chopsticks(i); |
|
|
|
EATING; |
|
|
|
drop_chopsticks(i); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
# The take_chopsticks procedure involves checking the status of neighboring |
|
|
|
# philosophers and then declaring one's own intention to eat. This is a two-phase |
|
|
|
# protocol; first declaring the status HUNGRY, then going on to EAT. |
|
|
|
|
|
|
|
procedure take_chopsticks(i) |
|
|
|
{ |
|
|
|
DOWN(me); # critical section |
|
|
|
pflag[i] := HUNGRY; |
|
|
|
test[i]; |
|
|
|
UP(me); # end critical section |
|
|
|
DOWN(s[i]) # Eat if enabled |
|
|
|
} |
|
|
|
|
|
|
|
void test(i) # Let phil[i] eat, if waiting |
|
|
|
{ |
|
|
|
if ( pflag[i] == HUNGRY |
|
|
|
&& pflag[i-1] != EAT |
|
|
|
&& pflag[i+1] != EAT) |
|
|
|
then |
|
|
|
{ |
|
|
|
pflag[i] := EAT; |
|
|
|
UP(s[i]) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
# Once a philosopher finishes eating, all that remains is to relinquish the |
|
|
|
# resources---its two chopsticks---and thereby release waiting neighbors. |
|
|
|
|
|
|
|
void drop_chopsticks(int i) |
|
|
|
{ |
|
|
|
DOWN(me); # critical section |
|
|
|
test(i-1); # Let phil. on left eat if possible |
|
|
|
test(i+1); # Let phil. on rght eat if possible |
|
|
|
UP(me); # up critical section |
|
|
|
} |
|
|
|
|
|
|
|
*/ |
|
|
|
|
|
|
|
|
|
|
|
//---------- philosophers problem using semaphore ---------------------- |
|
|
|
int state_sema[N]; /* 记录每个人状态的数组 */ |
|
|
|
/* 信号量是一个特殊的整型变量 */ |
|
|
@ -105,7 +167,7 @@ int philosopher_using_semaphore(void * arg) /* i:哲学家号码,从0到N-1 |
|
|
|
|
|
|
|
struct proc_struct *philosopher_proc_condvar[N]; // N philosopher |
|
|
|
int state_condvar[N]; // the philosopher's state: EATING, HUNGARY, THINKING |
|
|
|
monitor_t mt, *mtp=&mt; // mp is mutex semaphore for monitor's procedures |
|
|
|
monitor_t mt, *mtp=&mt; // monitor |
|
|
|
|
|
|
|
void phi_test_condvar (i) { |
|
|
|
if(state_condvar[i]==HUNGRY&&state_condvar[LEFT]!=EATING |
|
|
@ -128,7 +190,7 @@ void phi_take_forks_condvar(int i) { |
|
|
|
state_condvar[i]=HUNGRY; |
|
|
|
// try to get fork |
|
|
|
phi_test_condvar(i); |
|
|
|
while (state_condvar[i] != EATING) { |
|
|
|
if (state_condvar[i] != EATING) { |
|
|
|
cprintf("phi_take_forks_condvar: %d didn't get fork and will wait\n",i); |
|
|
|
cond_wait(&mtp->cv[i]); |
|
|
|
} |
|
|
|