1

I am looking at Peterson's Algorithm(mutual exclusion for 2 processes) My question is what if no processes has entered a critical section yet and P0 wants to enter a critical section for the first time, then P1's Flag would be false, so how does P0 enter it's critical section? The condition for P0 to enter it's critical section depends on our flag for P1 to be true.

Code:

    //flag[] is boolean array; and turn is an integer
flag[0]   = false;
flag[1]   = false;
turn;

P0: flag[0] = true;
    turn = 1;
    while (flag[1] == true && turn == 1)
    {
        // busy wait
    }
    // critical section
    ...
    // end of critical section
    flag[0] = false;

P1: flag[1] = true;
    turn = 0;
    while (flag[0] == true && turn == 0)
    {
        // busy wait
    }
    // critical section
    ...
    // end of critical section
    flag[1] = false;
user2122810
  • 93
  • 1
  • 3
  • 11

1 Answers1

3

The condition for P0 to enter it's critical section depends on our flag for P1 to be true.

No it doesn't. The statement...

while (flag[1] == true && turn == 1) { ... }

Is busy-waiting for the flag for P1 to stop being true. That is: P0 waits for P1 to leave its critical section. Since P1 has not yet entered its critical section, P0 doesn't busy-wait and enters the critical section correctly.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
  • Oh i got it, didn't see the waiting part, i thought it said while(){Critical section} Thank you for clearing that up, dumb of me., – user2122810 Mar 03 '13 at 16:59