What is Peterson's solution?

Peterson's solution was proposed to resolve the critical section problem involving only two processes. This solution guarantees that it provides mutual exclusion, bounded waiting, and progress of the processes.

The following code snippet shows how Peterson's algorithm works:

Algorithm for PiP_{i} process

 do{
  flag[i] = true;
  turn = j;
  while (flag[j] && turn == j);
  //critical section

  flag[i] = false;

  //remainder section
}while(true);

Algorithm for PjP_{j} process

do{
  flag[j] = true;
  turn = i;
  while (flag[i] && turn == i);
  //critical section

  flag[j] = false;

  //remainder section
}while(true);

Explanation

The processes and variables used in the algorithm need to be elaborated. Processes names used in this solution are Pi and Pj, respectively. There are two variables that the two processes share:

  • turn(int): The variable turn indicates whose turn it is to enter the critical section. If turn == i, then Pi is allowed to enter their critical section.

  • flag (boolean): The flag array indicates if a process is ready to enter the critical section. If flag[i] = true, then it means that process Pi is ready.

Let's consider the algorithm of process Pi, the process i first raises a flag indicating a wish to enter the critical section. Then, turn is set to j to allow the other process. The j enter the critical section. Finally, the while loop will only allow one process to enter its critical section.

The Process i lowers the flag[i] in the exit section allowing the process j to continue if it has been waiting.

Although it provides concurrency, Peterson's solution is limited to only two processes and involves busy waiting, which exhausts the systems' resources.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved