C 为什么彼得森';s的互斥解决方案要求回合==while循环中的进程作为条件?
我试图理解彼得森为互斥问题提供的解决方案。这就是彼得森的互斥解决方案:C 为什么彼得森';s的互斥解决方案要求回合==while循环中的进程作为条件?,c,operating-system,C,Operating System,我试图理解彼得森为互斥问题提供的解决方案。这就是彼得森的互斥解决方案: 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
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
}
我不明白他为什么在idle while循环中使用turn==进程。这看起来很矛盾,因为如果另一个进程想要进入关键区域,turn设置为另一个进程,这意味着前一个进程也可以进入关键区域,而不考虑相关缓冲区的内容
while(turn == process && interested[other] == TRUE); // wait
用于等待处于关键段或希望进入关键段的其他进程。在任何时间点,只有一个过程可以处于关键部分
所有其他进程都将在循环中while(turn==process&&interest[other]==TRUE)代码>当任何一个进程处于关键部分时
当关键部分中的进程从关键部分出来时,它将interest[process]
的值设置为FALSE
,然后使当前等待进程的条件turn==process&&interest[other]==TRUE
为FALSE,进程进入关键部分
用于等待处于关键段或希望进入关键段的其他进程。在任何时间点,只有一个过程可以处于关键部分
所有其他进程都将在循环中while(turn==process&&interest[other]==TRUE)代码>当任何一个进程处于关键部分时
当关键部分中的流程从关键部分出来时,它将感兴趣的[process]
的值设置为FALSE
,然后使条件转向==流程和感兴趣的[other]==TRUE
false当前等待流程,流程进入关键部分。考虑以下执行顺序,以了解为什么需要该条件:
“其他”进程执行以下操作:
interested[other] = TRUE
turn = other
此时,“其他”进程将切换出上下文,当前进程将执行:
interested[process] = TRUE
turn = process
因此,在这一点上,我们有:
interested[other] = TRUE
interested[process] = TRUE
turn = process
在这种情况下,“其他”过程将进入关键部分。但是这个过程不会像(turn==process&&interest[other]==TRUE)
那样是真的。此进程将等待另一进程执行interest[other]=FALSE代码>考虑以下执行顺序,以了解为什么需要该条件:
“其他”进程执行以下操作:
interested[other] = TRUE
turn = other
此时,“其他”进程将切换出上下文,当前进程将执行:
interested[process] = TRUE
turn = process
因此,在这一点上,我们有:
interested[other] = TRUE
interested[process] = TRUE
turn = process
在这种情况下,“其他”过程将进入关键部分。但是这个过程不会像(turn==process&&interest[other]==TRUE)
那样是真的。此进程将等待另一进程执行interest[other]=FALSE代码>两个答案都没有解决我的问题。我解释一下。英语不是我的母语。我们假设没有turn
变量。
两个线程可能都执行了感兴趣的[process]=TRUE代码>。这是可能发生的。例如,在执行感兴趣的[process]=TRUE之后,T1被关闭代码>。然后T2执行感兴趣的[process]=TRUE代码>,然后它遇到条件感兴趣的[other]==TRUE
,它就卡住了。然后T1被切换,它也会变成感兴趣的[other]==TRUE
,它也会被卡住。通过添加turn
,两个线程不能同时在感兴趣的[other]==TRUE&&turn==process
条件下失败(因为turn
不能等于两个不同的值),所以可以避免死锁。两个答案都没有解决我的问题。我解释一下。英语不是我的母语。我们假设没有turn
变量。
两个线程可能都执行了感兴趣的[process]=TRUE代码>。这是可能发生的。例如,在执行感兴趣的[process]=TRUE之后,T1被关闭代码>。然后T2执行感兴趣的[process]=TRUE代码>,然后它遇到条件感兴趣的[other]==TRUE
,它就卡住了。然后T1被切换,它也会变成感兴趣的[other]==TRUE
,它也会被卡住。通过添加turn
,两个线程不能同时在感兴趣的[other]==TRUE&&turn==process
条件下失败(因为turn
不能等于两个不同的值),因此可以避免死锁