我已经开始学习关键部分问题及其各种解决方案。为了解释我的问题,我先简要介绍一下它。
临界区问题的两个过程解决方案的一般结构 - 算法1是:
turn = 0;
do
{
while (turn != 0) ; //if not P0's turn , wait indefinitely
// critical section of Process P0
turn = 1; //after P0 leaves critical section, lets P1 in
//remainder section
} while (1); //loop again
该算法的问题在于它不支持Progress的必要要求。它通过P0 - > P1 - > P0 - > P1 - >强制关键部分拥有相等的转弯。为了解决这个问题,使用算法2,其中变量转换由数组flag[]
代替。算法2的一般结构是:
do
{
flag[0] = T ;
while (flag[1]);//if flag[1] is true wait indefinitely
// critical section of Process P0
flag [0] = F; //P0 indicated it no longer needs to be in critical section
//remainder section
} while (1); //loop again
在这里,进程可以在需要时重复执行其关键部分。 (虽然这个算法也不支持进度)
现在我的问题是,为什么我们不能在算法1中使用do-while循环中的变量转换,就像我们在算法2中使用变量flag[]
一样?下面的代码将解释我的意思:对于进程0:
do
{
turn = 0;
while (turn != 0) ; //if not P0's turn , wait indefinitely
// critical section of Process P0
turn = 1; //after P0 leaves critical section, lets P1 in
//remainder section
} while (1); //loop again
对于流程1:
do
{
turn = 1;
while (turn != 1) ; //if not P0's turn , wait indefinitely
// critical section of Process P0
turn = 0; //after P1 leaves critical section, lets P0 in
//remainder section
} while (1); //loop again
如果需要,上述代码是否允许进程重复执行其关键部分,从而解决算法1中的问题?我知道这里有问题,否则这个解决方案一般会被使用,不知道究竟是什么。
关键部分不再受到保护。在任意调度序列中有这一个(一行=在此期间由进程X独占执行):
process action contents of 'turn' critical section entered (by process)
0 "turn = 1;" 1 no
0 "} while(1);" 1 no
1 "while (turn != 1);" 1 no
1 "// critical section P1" 1 yes (1)
0 "do{" 1 yes (1)
0 "turn = 0;" 0 yes (1)
0 "while (turn != 0);" 0 yes (1)
0 "// critical section P0" 0 collision!