Here is the Peterson's solution presented in our lecture:
//P0:
do {
flag[0] = TRUE; turn = 1;
while(flag[1] && turn == 1);
//Critical section
flag[0] = FALSE;
//remainder section
} while(1)
//P1:
do {
flag[1] = TRUE; turn = 0;
while(flag[0] && turn == 0);
//critical section
flag[1] = FALSE;
//remainder section
} while(1)
Doesn't the turn variable itself already guaranteed the requirements for critical section? Like the flag[] here seems unnecessary.
The flag array specifies for each process whether it is currently interested in the critical section (i.e. whether it currently desires to enter it or is already inside it). This information is necessary for the following reason:
Assuming that process #0 desires to enter the critical section, it must know whether process #1 is currently also interested in the critical section, because process #0 must act differently depending on whether process #1 is also interested in the critical section.
If process #1 is not interested in the critical section, then process #0 should not wait for process #1 to set turn to 0, because it may wait indefinitely for this to happen, which would violate the "progress" and "bounded waiting" requirement. Instead, process #0 should simply enter the critical section in that case.
If process #1 is interested in the critical section, then process #0 should wait for process #1 to either
flag[1] to false), orturn to 0).Otherwise, the "mutual exclusion" requirement would be violated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With