Latest

6/recent/ticker-posts

What is Peterson's solution?

 As discussed in the post, What is Process Synchronization?, we came to know what is process synchronization and what is critical section problem.

Peterson's solution is a software based solution to the critical section problem. 

do

{

    flag[i]=true;

    turn=j;

    while (flag[j] && turn==j);

    CRITICAL SECTION

    flag[i]=false;

    REMAINDER SECTION

} while(true);

The above code is the basic structure of a process in Peterson's solution. The variable turn indicates whose turn it is to enter the critical section and flag[i] is used to indicate if a process is ready to enter it's critical section. 

In the entry section before entering critical section, process Pi sets the flag[i] value to true indicating that Pi is ready to enter it's critical section and then set the turn value to j asserting if any other process wants to enter the critical section they can do so to ensure progress. Then it execute the while loop until flag[j] is true and turn is j i.e. other process is using the critical section. After that if any of the above two conditions in the while loop becomes false, it can enter the critical section. In the exit section, it sets flag[i] to false indicating that it is leaving critical section.

If both processes try to enter the critical section at the same time, turn value will be set to i and j apparently at the same time and the first turn value will be overwritten immediately, the one which will make change in the turn value first will get to enter the critical section.

Peterson's solution preserves all the conditions mutual exclusion, progress and bounded waiting.

When both the processes are ready to enter critical section i.e. flag[i]==flag[j]==true, both cannot enter the critical section at the same time because only one while loop will get executed as the value of turn can be either i or j not both at the same time. Hence ensures mutual exclusion. 

Process Pi can be prevented from entering critical section if it is stuck in the while loop i.e. when turn==j and flag[j]==true. But if Pj is not ready to enter the critical section, then flag[j]=false and then Pi can enter the critical section. If flag[j]=false, then turn value must be i and in the while loop, Pi cannot change the turn value, that's why Pi will get to enter the critical section after at most one entry of Pj ensuring both progress and bounded waiting.

IMPORTANT POINTS:

  • Peterson's solution is restricted to two processes that alternate executions between their critical section and remainder section.
  • The shared data by the two processes P0 and P1 in Peterson's solution are: 
            int turn;
            boolean flag[2];
  • flag[i] indicates that process Pi is ready to enter the critical section and turn =j makes sure that if the other process is also ready to enter the critical section, then it can enter before i ensuring mutual exclusion.



Post a Comment

0 Comments