7

I have read this for Peterson's algorithm for mutual exclusion.Then there was the question what will happen if we reorder the first and second command in the do...while loop? I cannot see something happening if we do that...Can someone tell me what I am missing?

do {
     flag[me] = TRUE;
     turn = other;
     while (flag[other] && turn == other)
             ;
     critical section
     flag[me] = FALSE;
     remainder section
   } while (TRUE);
Saraki
  • 297
  • 1
  • 7
  • 21

1 Answers1

7

If you reorder those two commands, you'll get these two processes running concurrently:

turn = 1;                       |      turn = 0;
flag[0] = true;                 |      flag[1] = true;
while(flag[1] && turn==1)       |      while(flag[0] && turn==0)
    ;                           |          ;
critical section 0              |      critical section 1
flag[0] = false;                |      flag[1] = false;

That may happen to execute in the following order:

Process 1: turn = 0;
Process 0: turn = 1;
Process 0: flag[0] = true;
Process 0: while(flag[1] && turn==1) // terminates, since flag[1]==false
Process 0: enter critical section 0
Process 1: flag[1] = true;
Process 1: while(flag[0] && turn==0) // terminates, since turn==1
Process 1: enter critical section 1
Process 0: exit critical section 0
Process 1: exit critical section 1

Which violates the mutual exclusion criterion.

Anton
  • 3,113
  • 14
  • 12