The Peterson algorithm simplifies the implementation of process mutex relative to the Dekker algorithm (see process Mutex (ii) Dekker algorithm).
Suppose there are two processes that require mutually exclusive access to a critical section.
The Peterson algorithm has the following form:
Enterregion (process);//processes represent the progress number//critical area leaveregion (process);
The implementation is as follows (Java implementation):
There are two global variables:
Used to indicate which process the private int turn;//uses to indicate the intention of the process to enter the critical section, the subscript corresponding to the process number private boolean[] interested = new boolean[] {false, false};
The Enterregion method is implemented as follows:
/** * @param process number */public void enterregion (int process) {//process number of another process int other = 1-process;//process to enter the critical section int Erested[process] = true;//Set the turn itself into the critical section turn = process;/** * When two processes want to enter the critical section at the same time, their interested[process] is true, However, the turn value set by the latter process overrides the turn value set by the previous process, so the turn = = Process condition of the latter process is true, and it waits in that while loop *, while the previous process's turn = = Process condition is false and can enter the critical section smoothly. After the previous process leaves the critical section, the latter process can also enter the critical section */while (turn = = Process && Interested[other] = = True) {}}
The Leaveregion method is implemented as follows:
public void leaveregion (int process) {interested[process] = false;}
Process Mutex (c) Peterson algorithm