Critical Section Problem: Algorithm 2


Algorithm 1 does not remember the state of each process. Instead of a single integer variable, try an array of boolean values:

var flag: array [0..1] of boolean;

The array elements are initialized to false. If flag[i] is true then process Pi is executing its critical section.


repeat

        flag[i] := true;
        while flag[j] do no-op;

                critical section

        flag[i] := false;

                remainder section

until false;


This algorithm can fail the progress requirement if both processes set their flags to true and then both execute the while loop.

Swapping the while and the assignment flag[i] := true doesn't help either -- in this case we can't guarantee mutual exclusion.