Go directly to the code
1 #defineN 5/* Number of philosophers */2 #defineTheir neighbourhood number of left (i+n-1)%N/* I */3 #defineRight (i+ 1)%N/* I number */4 #defineThinking 0/* philosopher in thinking * *5 #defineHungry 1/* philosopher tries to pick up a fork */6 #defineEATING 2/* Philosopher's Dinner * *7typedefintSemaphore/*Signal Volume*/8 intState[n];/*record each philosopher's state*/ 9Semaphore Mutex =1;/*Mutual exclusion of critical sections*/TenSemaphore S[n];/*each philosopher a semaphore*/ One A voidPhilosopher (intI/*I: Philosopher number, from 0 to N-1*/ - { - while(TRUE) {/*Infinite Loops*/ theThink ();/*Philosophers Thinking*/ -Take_ Forks (i);/*Test if the fork is available*/ -Eat ();/*Philosophers Dine*/ -Put_ Forks (i);/*put the fork back on the table*/ + } - } + A voidTake_forks (intI at { -Down (&mutex);/*Enter the critical section*/ -State[i] = hungry;/*record philosopher I in a state of starvation*/ -Test (i);/*try to get two forks*/ -Up (&mutex);/*Exit critical Section*/ -Down (&s[i]);/*If you don't get the fork you need, it's blocked.*/ in } - to voidPut_forks (i) + { -Down (&mutex);/*Enter the critical section*/ theState[i] =thinking;/*The philosopher is finished eating*/ *Test (left);/*test whether their neighbourhood can eat*/ $Test (right);/*test whether the right neighbor can eat*/ Panax NotoginsengUp (&mutex);/*leave the critical section*/ - } the + voidTest (i)
A { the if(State[i] ==hungry && state[left]! = EATING && state[right]! =EATING) { +State[i] =EATING; -Up (&S[i]); $ } $}
A philosopher is allowed to enter the dining state only when two neighbors are not eating!
The question of the Philosopher's meal