Scenario: Both P0 and P1 request the critical section at the same time
Assume initially: turn = 0, want[0]=false, want[1]=false.
Now both set their flags to true almost simultaneously.
| Step |
P0 (i=0, j=1) |
P1 (i=1, j=0) |
| 1 |
want[0] = true |
want[1] = true |
| 2 |
Sees want[1] == true → enters while-loop |
Sees want[0] == true → enters while-loop |
| 3 |
Checks turn == 1 → false (since turn=0) → does not back off |
Checks turn == 0 → true → backs off: want[1]=false |
| 4 |
Now sees want[1] == false → enters critical section |
Waits while turn == 0 (spin), then retries later |
| 5 |
On exit: sets turn = 1, then want[0]=false |
Now turn == 1 → stops waiting, sets want[1]=true again, and enters CS next |
Takeaway
When both want to enter, exactly one backs off due to turn. This prevents deadlock and enforces mutual exclusion.