书上的解法是用碗的数量来做互斥信号量,最多n-1个人等待拿筷子,即使都拿起来了一根筷子,还剩下一根筷子会使得他们可以吃饭。
semaphore bowl = min(n - 1, m);
semaphore chopsticks[n] = {1};
CoBegin
Philosopher_i() {
while(1) {
think;
P(bowl);
P(chopsticks[i]);
P(chopsticks[(i + 1) % n]);
eat;
V(chopsticks[i]);
V(chopsticks[(i + 1) % n]);
V(bowl);
}
}
CoEnd
我的解法:按照之前知识点讲解里,设个mutex来拿筷子,拿完筷子才能拿碗,再吃饭。不知是否正确。
semaphore bowl = m;
semaphore chopsticks[n] = {1};
semaphore mutex = 1;
CoBegin
Philosopher_i() {
while(1) {
think;
P(mutex);
P(chopsticks[i]);
P(chopsticks[(i + 1) % n]);
P(bowl);
eat;
V(bowl);
V(chopsticks[i]);
V(chopsticks[(i + 1) % n]);
V(mutex);
}
}
CoEnd