Search code examples
processflagscritical-sectionmutual-exclusion

Unclearance in mutual exclusion example


I have read several examples about mutual exclusions, and I can understand the run of most of them except the following example handed to me:

boolean[] flag = new boolean[2]; 

enter image description here

one while-condition is depending on the flag[n] state of the other process. So in order to for example have P1 heading into it's critical section both flag[0] and flag[1] need to be set true.

According to my interpertation the entire run will have to look like this:

P1 - > flag[1] = true
while(flag[0])            // flag[0] is still state-undeclared
P2  -> flag[0]  = true    // so P0 must set it true(?)
critic1(); 
while(flag[1]) 
critic2(); 

Though this can't be correct since with flag[0] and flag[1] set to true both processes pass the while(flag[n]) condition and a race-condition could still occur. What am I misunderstanding?


Solution

  • The declaration and definition

    boolean[] flag = new boolean[2]; 
    

    looks like java, and in java the boolean array is filled with false as default values.

    So in order to for example have P1 heading into it's critical section both flag[0] and flag[1] need to be set true.

    No that is not the case, for P1 to be heading into the Critical Section, only thing is that following statement of P0 must not be executed before P1 enters the Critical Section.

    flag[0] = true;
    

    and since by default flag[0] = false, the loop condition while(flag[0]) will be false and P1 will enter the critical section.

    If processes P0 and P1 are scheduled in such a way that the following statements are executed for both processes before the corresponding next statement:

    flag[0] = true; and flag[1] = true;
    

    In such case deadlock will occur.