进程间通信(四)--Peterson算法

xiaoxiao2021-02-28  124

两个进程都想进入临界区。

该算法思路:

enterRegion(int process);//进入临界区 criticalRegion();//临界区 leaveRegion(int process);离开临界区

全局变量:

private int turn;//轮到哪一个进程进入临界区 private boolean[] interested = new boolean[]{false,false}//进程打算进入临界区的意愿,下标代表进程号 核心方法:

public void enterRegion(int process){ int other = 1 - process;//表示另一个进程号 interested[process] = true;//表示自己想要进入临界区的意愿 turn = process;//设置轮到自己进入临界区 //如果轮到自己进入临界区但是其他进程在临界区中,只能循环等待 while(turn == process && interested[other] == true){} } public void leaveRegion(int process){ interested[process] = false; }

当两个进程都打算进入临界区的时候,都会进入enterRegion()方法:首先都会设置interested为true,然后设置turn为自己;但是turn为全局变量,只有最后写入的进程号才有效,前一个会因重写而被覆盖掉。后一个进程turn==process为真,并且interested[other]==true也为真,因此只能循环等待,直到前一个进程离开临界区导致interested[other]==true为假时,才能结束循环等待,进入到临界区中。 第一个写入turn的进程会首先进入临界区,等到离开临界区后,后一个进程才能进入临界区。
转载请注明原文地址: https://www.6miu.com/read-47388.html

最新回复(0)