Operating System-solutions for mutual exclusion between processes-ensure that only one process enters the critical section at a time (2)-Peterson solution, system-peterson
This article continues with the previous article about how to allow only one process to enter the critical section at a time. This article mainly introduces the Peterson solution.
Summary
1. Peterson Solution
Based on lock variables and strict rotation methods, a master named Peterson provided a simpler method to solve the mutual exclusion between processes.
Code
# Define N 2 // The number of processes is 2int turn; // which process is the current turn? Int interested [N]; // set initialization to false, that is, void enter_region (int process) that does not wait for reading or writing shared data in the critical section. // enter the critical section {turn = process; int other = 1-turn; // another process interested [turn] = true; while (turn = process & interested [other] = true); // always loops, until the other process exits the critical section} void leave_region (int process) {interested [process] = false ;}
The code is very refined, mainly through the combination of two variables, a turn and an interested [] array.
Ii. Code Analysis
- Only when process 0 is entered: turn = 0, other = 1, interested [0] = true, interested [1] = false. enter_region returns immediately, and process 0 immediately enters the critical section.
- Process 0 enters the critical section, but it has not left the critical section. At this time, process 1 enters the critical section, and turn to 1, interested [1] = true. Other = 0. But since process 0 has not left the critical section, interested [0] = interested [other] remains true. At this time, process 1 will always execute while in enter_region until process 0 leaves the critical section and sets interested [0] to false.
In an extreme case, Process 0 and Process 1 call enter_region almost simultaneously. In the end, there must be a thread that overwrites the data of another thread. Assume that process 1 overwrites process 0, at this time, turn is 1. Interested [0] = interested [1] = true.
- Process 0 will immediately enter the critical section without executing the while LOOP
- Process 1 will be block, because at this time turn = 1 & interested [0] = true, meets the while loop.
This code is really beautiful. I don't know how to describe it. I can only try it again.