Sar*_*aki 7 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);
Run Code Online (Sandbox Code Playgroud)
如果您重新排序这两个命令,您将使这两个进程同时运行:
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;
Run Code Online (Sandbox Code Playgroud)
这可能会按以下顺序执行:
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
Run Code Online (Sandbox Code Playgroud)
这违反了互斥准则。