Consider the following Barrier method to implement synchronization :
void barrier
{
P(s);
process_arrived++;
V(s);
while(process_arrived != 3);
P(s);
process_left++;
if(process_left == 3)
{
process_Arrived = 0;
process_left = 0;
}
V(s);
}
It is known that this code does not work because of a flaw, but I am not able to find the flaw.
答案 0 :(得分:1)
问题在于条件:if(process_left == 3)
如果立即连续使用两个屏障调用,可能会导致死锁。
最初,process_arrived和process_left将为' 0'。
当进程到达时,它会递增process_arrived并等待,直到达到最大进程数。之后,允许进程离开。
考虑以下情况:
P1来了,等到process_arrived变为3(当前process_arrived = 1)
P2来等待,直到process_arrived变为3(当前process_Arrived = 2)
现在P3来执行。 while循环中的条件失败并进一步执行,使process_left = 1并再次立即进入函数
它使process_Arrived = 4并在while循环中等待。
P2有机会执行make process_left = 2并离开。
P1进一步执行并发现process_left = 3,从而使process_arrived和process_left都为0.(请记住,P3已经进入并且正在等待屏障,所以此处计数丢失)
P1再次执行,使process_arrived = 1并等待。
P2也会再次执行。使process_arrived = 2并等待。
现在每个进程都会等待。因此发生了僵局。