使用以下代码通过监视器解决餐饮哲学家问题。我不明白为什么test()方法需要
self[i].signal();
我理解的方式是,当一个人存在其关键部分时,就会调用信号,即。当哲学家吃完之前,而不是之前。在这种情况下,如果一个人调用resource.pickup()然后将philosopher i设置为hungry,则调用test()以查看BOTH chopstick现在是否可用(这与信号量解决方案相比是主要优势)。然而,在test()中,如果两个邻居都没有进食而且我饿了,请拨打signal()??!我理解的方式是,signal()增加了资源计数器,并在一个人离开它的关键部分时被调用(我们在putdown()中看到,我不明白为什么它在这里被称为
// Dining-Philosophers Solution Using Monitors
monitor DP
{
status state[5];
condition self[5];
// Pickup chopsticks
Pickup(int i)
{
// indicate that I’m hungry
state[i] = hungry;
// set state to eating in test()
// only if my left and right neighbors
// are not eating
test(i);
// if unable to eat, wait to be signaled
if (state[i] != eating)
self[i].wait;
}
// Put down chopsticks
Putdown(int i)
{
// indicate that I’m thinking
state[i] = thinking;
// if right neighbor R=(i+1)%5 is hungry and
// both of R’s neighbors are not eating,
// set R’s state to eating and wake it up by
// signaling R’s CV
test((i + 1) % 5);
test((i + 4) % 5);
}
test(int i)
{
if (state[(i + 1) % 5] != eating
&& state[(i + 4) % 5] != eating
&& state[i] == hungry) {
// indicate that I’m eating
state[i] = eating;
// signal() has no effect during Pickup(),
// but is important to wake up waiting
// hungry philosophers during Putdown()
self[i].signal();
}
}
init()
{
// Execution of Pickup(), Putdown() and test()
// are all mutually exclusive,
// i.e. only one at a time can be executing
for
i = 0 to 4
// Verify that this monitor-based solution is
// deadlock free and mutually exclusive in that
// no 2 neighbors can eat simultaneously
state[i] = thinking;
}
} // end of monitor