如果我们重新排序Peterson的互斥算法中的命令,会发生什么?

时间:2014-03-15 16:39:44

标签: algorithm command mutual-exclusion

我已经阅读了Peterson的互斥算法。然后有一个问题,如果我们在do ... while循环中重新排序第一个和第二个命令会发生什么?如果我们这样做,我看不到发生的事情...有人能告诉我我错过了什么吗?

do {
     flag[me] = TRUE;
     turn = other;
     while (flag[other] && turn == other)
             ;
     critical section
     flag[me] = FALSE;
     remainder section
   } while (TRUE);

1 个答案:

答案 0 :(得分:2)

如果重新排序这两个命令,您将同时运行这两个进程:

turn = 1;                       |      turn = 0;
flag[0] = true;                 |      flag[1] = true;
while(flag[1] && turn==1)       |      while(flag[0] && turn==0)
    ;                           |          ;
critical section 0              |      critical section 1
flag[0] = false;                |      flag[1] = false;

可能会按以下顺序执行:

Process 1: turn = 0;
Process 0: turn = 1;
Process 0: flag[0] = true;
Process 0: while(flag[1] && turn==1) // terminates, since flag[1]==false
Process 0: enter critical section 0
Process 1: flag[1] = true;
Process 1: while(flag[0] && turn==0) // terminates, since turn==1
Process 1: enter critical section 1
Process 0: exit critical section 0
Process 1: exit critical section 1

这违反了互斥标准。