Peterson’s algorithm for mutual exclusion

Peterson’s algorithm for mutual exclusion was developed by G.L. Peterson in 1981. It provides a solution to the problem of critical region for two or more processes. The generalized algorithm structure is given below:

#define FALSE 0
#define TRUE 1
#define N 2
int turn;
int flag[N];
void enter_cr_region(int i);
int j;
j = 1 – i;
flag[i] = TRUE;
turn = i;
while (turn == i && flag[j] == TRUE)
void leave_cr_region(int i)
flag[i] = FALSE;

Here, before entering critical a process calls enter_cr_region with its process number as parameter. The result of this call can be that either the process can enter the critical region or has to wait for the other process to leave the critical region. For Example, a Process 0 calls enter_cr_region and indicates its interest that it wants to enter critical region by setting turn to 0. Now, when Process 1 wants to enter critical region it has to wait until flag[0] is false. flag[0] will be false only when Process 0 calls leave_cr_region and exits critical region.

Leave a Reply