An attempt to understand the Peterson algorithm

I am trying to understand the Peterson algorithm, and I came across this question. I traced the code and I wrote my observations. Please check my observation, am I on the right track?

Question from the textbook. Suppose there are only two processes: one with a pidvalue of 0 and one with a pidvalue of 1. What is wrong with this concurrency algorithm?

  while(True)
    {
     flag[pid] = 1
     turn = 1-pid
     while( flag[1-pid] && turn == 1-pid ); // busy wait

     // critical section
     ...
     // end of critical section

     flag[pid] = 0
    }

Code Tracking:

    ---------- Process 0: ---------- | ---------- Process 1: ----------
                                     |
    pid = 0                          |    pid = 1
    flag[0] = 1                      |    flag[1] = 1
    turn = 1 - 0 = 1                 |    turn = 1 - 1 = 0
                                     |
    while (flag[1 - 0]               |    while (flag[1 - 1]    
            && turn == (1 - 0))      |            && turn == (1 - 1))
                                     |
    // --> while (flag [1] && true)  |    // --> while (flag [0] && true)
    // --> while (flag [1])          |    // --> while (flag [0])

My observations

  • I think that in busy waiting sections, both loops can run forever.
  • , , process 0, , false (flag[0] = 0) . , 0 , 1 . , 1 .
+4
1

.

  • flag critical section.
  • turn , critical section.
  • critical section, , (flag[pid] = False). . , , - , flag "" "", , turn.

, :

I would like to access the critical section. So, I'll wait my turn


, , . , , .

+4

All Articles