The Algorithm
The algorithm uses two variables, flag and turn. A flag value of true indicates that the process wants to enter the critical section. The variable turn holds the ID of the process whose turn it is. Entrance to the critical section is granted for process P0 if P1 does not want to enter its critical section or if P1 has given priority to P0 by setting turn to 0.
//flag is boolean array; and turn is an integer flag = false; flag = false; turn; | |
P0: flag = true; turn = 1; while (flag == true && turn == 1) { // busy wait } // critical section ... // end of critical section flag = false; | P1: flag = true; turn = 0; while (flag == true && turn == 0) { // busy wait } // critical section ... // end of critical section flag = false; |
The algorithm does satisfy the three essential criteria to solve the critical section problem, provided that changes to the turn
, flag
, and flag
variables propagate immediately and atomically. The three criteria are mutual exclusion, progress, and bounded waiting.
Read more about this topic: Peterson's Algorithm