operating-system - 操作系统 : Peterson's solution

标签 operating-system synchronization critical-section

我正在尝试了解彼得森的同步解决方案。作为引用,我附上阅读来源: enter image description here

这是来自维基百科页面。现在, 假设P1想要进入临界区。它设置flag<a href="/image/Gtizp.png" rel="noreferrer noopener nofollow">1</a> = trueturn=0 。如果P0已经在其临界区,P1将在其while循环中持续等待 while(flag[0] == true && turn ==0) flag[0] = true 。 我的疑问是:

  1. 这种情况会发生什么:P1 正在执行其 while 循环,而当 P0 试图进入临界区并执行 线flag[0] = true 。由于某种原因,它无法执行下一行并终止。在此,flag[0] 也是 true 并且 turn 也是 0。当内部没有进程时,P1 不必要地等待 临界区。
  2. 为什么需要检查 turn多变的。为什么不仅是这个: while(flag[0]== true)一旦P0 从临界区离开,flag[0] = false 并且 P1 将能够 输入。

我对这个同步问题有点困惑,任何帮助将不胜感激。

最佳答案

  1. Why it needs to check for the turn variable. Why not only this: while(flag[0]== true) As soon as P0 will leave from critical section, flag[0] = false and P1 will be able to enter

如果您只使用 flag[0] 和 flag[1],则会导致死锁。让我们考虑 P0 设置 flag[0] = true 并继续检查 while 循环中的条件。在 P0 可以将 flag[1] 值加载到寄存器中进行比较之前,P1 设置 flag[1] = true。所以现在 P0 加载值 true 并将继续等待,并且由于 flag[0] 也为 true 并且 P0 陷入 while 循环中,P1 也将等待 while 循环。这是一个死锁情况,因为双方都在等待对方将标志值更改为 false。

  1. What will happen in the case: P1 is executing its while loop and when P0 just tries to enter the critical section and executed the line flag[0] = true . Due to some reason, it couldnt't execute the next line and terminated. In this, flag[0] is also true and turn is also 0. P1 unnecessarily waits while no process is inside the critical section.

对于这个问题,我不认为 P0 突然终止证明 Peterson 同步解决方案的实现是错误的。这是程序中的缺陷,任何有缺陷的代码都可能导致这种死锁情况。

关于operating-system - 操作系统 : Peterson's solution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44548339/

相关文章:

c - 将CPU和内存管理模型整合在一起

linux - 优先级调度 OS bash 文件

java stacktrace 显示一个阻塞的线程,但没有关于阻塞它的信息

android - 在不需要 AccountAuthenticator 时使用 SyncAdapter

c++ - 关键部分在线程或主程序中更好?

c++ - Mutex 示例中未处理的异常/访问冲突写入位置

multithreading - 监视器与互斥体

javascript - 主干(同步)更新事件

parallel-processing - MPI 中的临界区?

unit-testing - uC/OS 的单元测试 - II