Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peterson's Algorithm with some modifications

Tags:

algorithm

would Peterson's Algorithm work after flipping the turn and flag orders; ex:

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

=================

P1:
  turn = 0;
  flag[1] = true;
         while (flag[0] && turn == 0)
         {
             // busy wait
         }
         // critical section
         ...
         // end of critical section
         flag[1] = false;
like image 567
Mr_X Avatar asked May 08 '26 14:05

Mr_X


1 Answers

No, it doesn't work if you flip the orders, because it allows both processes to enter the critical section simultaneously.

For example, suppose an initial state where flag[0] = false, flag[1] = false, turn = 0:

Process 0 runs:

turn = 1;  // flag[0] = false, flag[1] = false, turn = 1

Then context switch to process 1:

turn = 0;
flag[1] = true;   // flag[0] = false, flag[1] = true, turn = 0

while (flag[0] && turn == 0) {} // this evaluates to false because
    // process 0 was interrupted before it set flag[0] to true

// Process 1 enters the critical section...

Then context switch back to process 0:

flag[0] = true;   // flag[0] = true, flag[1] = true, turn = 0
while (flag[1] && turn == 1) {} // this evaluates to false

// Process 0 enters the critical section..

Now both processes are inside the critical section.

Setting the flag has to come first because it's the thing that the other process can't overwrite. If a process sets turn then as shown above the other process can overwrite it and then enter the critical section before the first process has a chance to set the flag.

like image 54
samgak Avatar answered May 10 '26 08:05

samgak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!