Thank blogger Http://blog.csdn.net/speedme/article/details/17595821
1. Background First of all, for example, the process p1,p2 a variable count, with an initial value of 0
Because the order of execution of the P1,P2 two processes is random, possible sequential execution may also be concurrent, visible by the diagram, different execution order, the value of count will be different, which is not allowed. In this case, multiple processes concurrently access and manipulate the same data and the execution results are related to the particular order in which the access occurs, called a race condition.
2. Critical area problem in order to avoid the occurrence of the above-mentioned situation, the concept of critical region is introduced. A system has n processes, and each process has a code snippet called a critical section. An important feature of this system is that when a process is executed within a critical section, no other process is allowed to execute within the critical section. The critical area problem must satisfy three principles: mutual exclusion, forward, limited waiting. The explanation is as follows: After the 3.Peterson algorithm understands the critical section, how to control the two processes accessing a shared unit user resource without an access violation. The Peterson algorithm is a concurrency programming algorithm for mutual exclusion, which solves this problem well. Let's take a look at two programs that are not the algorithm
Careful analysis of the above two pieces of code to know when the multi-process execution code they are violating the progress principle (critical section three principle). The Peterson algorithm code is as follows: The critical section Three principle is well met. The median turn was used to avoid.
Pi process PJ process (swap I, J position can be)
Pseudo code
Java Code Implementation
public class Peterson implements Runnable {private static boolean[] in = {false, false};
private static volatile int turn =-1;
public static void Main (string[] args) {new Thread (new Peterson (0), "Thread-0"). Start ();
New Thread (New Peterson (1), "Thread-1"). Start ();
} private final int id;
Public Peterson (int i) {id = i;
} private int Other () {return id = = 0? 1:0;
} @Override public void Run () {In[id] = true;
turn = Other ();
while (In[other ()] && turn = = Other ()) {System.out.println ("[" + ID + "]-waiting ..."); } System.out