我试图了解彼得森提供的互斥问题的解决方案。所以这是Peterson的互斥解决方案:
int No_Of_Processes; // Number of processes
int turn; // Whose turn is it?
int interested[No_Of_Processes]; // All values initially FALSE
void enter_region(int process) {
int other; // number of the other process
other = 1 - process; // the opposite process
interested[process] = TRUE; // this process is interested
turn = process; // set flag
while(turn == process && interested[other] == TRUE); // wait
}
void leave_region(int process) {
interested[process] = FALSE; // process leaves critical region
}
我不明白为什么他在空闲while循环中使用turn == process。它看起来很矛盾,因为如果另一个进程想要进入关键区域,则将turn设置为另一个进程,这意味着前一个进程可以进入关键区域,同时忽略感兴趣缓冲区的内容。
答案 0 :(得分:0)
while(turn == process && interested[other] == TRUE); // wait
用于等待临界区中的其他进程或想要进入临界区。在任何时间点,只有一个过程可以处于关键部分。
所有其他进程都在循环while(turn == process && interested[other] == TRUE);
中,而任何一个进程都在关键部分。
当关键部分中的流程出现在关键部分时,它将interested[process]
的值设置为FALSE
,然后使条件turn == process && interested[other] == TRUE
为当前等待进程的错误进入关键部分。
答案 1 :(得分:0)
考虑下面的执行顺序,以了解为什么需要这个条件:
"其他"进程执行以下操作:
interested[other] = TRUE
turn = other
此时"其他"进程获取上下文并执行当前进程:
interested[process] = TRUE
turn = process
所以在这一点上我们有:
interested[other] = TRUE
interested[process] = TRUE
turn = process
在这种情况下,"其他"进程将进入关键部分。但是这个过程不会像(turn == process && interested[other] == TRUE)
那样真实。此过程将一直等到另一个进程执行interested[other] = FALSE;
。
答案 2 :(得分:0)
两个答案都没有解决我的问题。我给出一个解释。英语不是我的母语。我们假设没有 turn
变量。
两个线程可能都执行了 interested[process] = TRUE;
。这可能发生。例如,T1 在执行 interested[process] = TRUE;
后立即被关闭。然后T2执行interested[process] = TRUE;
,然后到了条件interested[other] == TRUE
,就卡住了。然后T1被切入,也到了interested[other] == TRUE
,也卡住了。通过添加turn
,两个线程不能同时在interested[other] == TRUE && turn == process
条件下失败(因为turn
不能不等于两个不同的值),因此可以避免死锁。