【问题标题】:Why does peterson's solution for mutual exclusion require turn == process as condition in while loop?为什么彼得森的互斥解决方案需要将转==过程作为while循环中的条件?
【发布时间】:2017-04-29 22:14:44
【问题描述】:

我正在尝试了解 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 == 进程。这看起来很矛盾,因为如果另一个进程想要进入临界区,则将轮次设置为另一个进程,这意味着前一个进程也可以进入临界区,而不管感兴趣的缓冲区的内容。

【问题讨论】:

    标签: c operating-system


    【解决方案1】:

    考虑以下执行顺序以了解为什么需要该条件:

    “其他”进程执行以下操作:

    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】:
      while(turn == process && interested[other] == TRUE); // wait
      

      用于等待处于临界区或想进入临界区的其他进程。任何时候都只能有一个进程处于临界区。

      所有其他进程都将在循环中while(turn == process && interested[other] == TRUE);,而任何一个进程都在临界区。

      当临界区中的进程从临界区出来时,它将interested[process]的值设置为FALSE,这使得当前等待进程的条件turn == process && interested[other] == TRUE为假,进程进入临界区.

      【讨论】:

        【解决方案3】:

        这两个答案都没有解决我的问题。我给出一个解释。英语不是我的母语。我们假设没有turn 变量。 两个线程可能都执行了interested[process] = TRUE;。这可能发生。例如,在执行interested[process] = TRUE; 之后,T1 就被关闭了。然后T2执行interested[process] = TRUE;,然后到了interested[other] == TRUE这个条件,就卡住了。然后T1开机,也到interested[other] == TRUE,也卡住了。通过添加turn,两个线程不能同时在interested[other] == TRUE && turn == process条件下失败(因为turn不能不等于两个不同的值),因此可以避免死锁。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-05
          • 1970-01-01
          相关资源
          最近更新 更多