Peterson algorithm
The Peterson algorithm, also known as the Peterson solution, is a concurrent programming algorithm for mutual exclusion, which allows two or more processes or threads to execution sharing a resource without conflicts, using only shared memory for communication.
Gary L. Peterson developed the basic algorithm for two processes in 1981, as a simplification of Dekker's algorithm. The basic algorithm can easily be generalized to an arbitrary number of processes.
Algorithm for two processes
Flag[chuckles]0] = false Flag[chuckles]1] = false shift // It is not necessary to assign a shift p0: Flag[chuckles]0] = bar p1: Flag[chuckles]1] = bar shift = 1 shift = 0 while( Flag[chuckles]1] " fake " shift ♪ 1 ); while( Flag[chuckles]0] " fake " shift ♪ 0 ); //{ does nothing; wait. {//does nothing; wait. ! // critical section // critical section // end of critical section // end of critical section Flag[chuckles]0] = false Flag[chuckles]1] = false
Processes p0 and p1 cannot be in the critical section at the same time: if p0 is in the critical section, then flag[0] = true, and it happens that flag[1] = false, so p1 has the critical section is over, or the shared variable turn = 0, so p1 is waiting to enter the critical section. In both cases, p1 cannot be in the critical section.
Algorithm for N processes
// Shared variablesFlag: array[chuckles]0..N-1] of -1..n-2; /* initialized to -1 */shift: array[chuckles]0..N-2] of 0..n-1; * Initialized to 0 */// Protocol for Pi (i=0,...,N-1)j:0..N-2; /* local variable indicating stage */for j = 0 to N-2{ Flag[chuckles]i] = j; shift[chuckles]j] = i; while [consuming k I was. i : Flag[chuckles]k] ≥ j) ∧ (shift[chuckles]j] ♪ i)] do; !.Section Criticism▪Flag[chuckles]i] = -1;