来自 here
The global variable turn is used to indicate the next process to enter the critical section. The initial value of turn can be 0 or 1.
int turn = 1;
T0:
while (true) {
while (turn != 0) { ; } (1)
critical section (2)
turn = 1; (3)
non-critical section (4)
}
T1:
while (true) {
while (turn != 1) { ; } (1)
critical section (2)
turn = 0; (3)
non-critical section (4)
}
我不明白这是什么问题。为什么 T0 会永远重复 while (turn != 1)
?如果上下文切换到 T1,那么它将进入它的临界区,然后设置 turn=0
。
编辑:我现在明白为什么 T0 会永远等待了。被违反的“规则”有名称吗?例如,在线程上下文中有“互斥”、“进度”、“有界等待”和“无假设”线程/进程的相对速度”那么其中之一是否未满足?
最佳答案
您缺少问题描述中的第二个假设: 线程可能会在非关键部分终止。您在此处复制的描述指定“T1 在非关键部分终止”,因此 T1 永远不会再设置 turn=0。
关于multithreading - 这种确保临界区不被中断的算法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19234331/