Operating System
Operating System
6.3 The first known correct software solution to the critical-section problem for two
processes was developed by Dekker. The two processes, P0 and P1, share the following
variables:
boolean flag[2]; /* initially false */
int turn;
The structure of process Pi (i = 0 or 1), with Pj (j = 1 or 0) being the other process, is
shown in Figure 7.27.
Prove that the algorithm satisfies all three requirements for the critical-section problem.
do{
flag[i]=true;
while(flag[j]){
if(turn==j){
flag[i]=false;
while(turn==j);
flag[i]=true;
}
}
Critical section
turn = j;
flag[i]=false
Remainder section
}while(1);
Figure 7.27 The structure of process Pi in Dekker's algorithm.
Answer: To prove property (a) we note that each Pi enters its critical section only if flag[j] =
false. Since only Pi can update flag[j], and since Pi inspects flag[j] only while flag[i]=true,
the result follows.
a. To prove property (b), we first note that the value of the variable turn is changed only at
the end of the critical section. Suppose that only process Pi wants to enter the critical section.
In this case, it will find flag[j]=false and immediately enter the critical section, independent
of the current value of turn. Suppose that both processes want to enter the critical section, and
the value of turn = 0. Two cases are now possible. If Pi finds flag[0] = false then it will enter
the critical section. If Pi finds flag[0] = true then we claim that P0 will enter the critical
section before P1. Moreover, it will do so within a finite amount of time.
b. To demonstrate this fact, first consider process P0. Since turn = 0, it will only be waiting
for flag[1] to be set to false; more precisely, it will not be executing in the begin block
associated with the if statement. Furthermore, it will not change the value of flag[0].
Meanwhile, process P1 will find flag[0] = true and turn = 0. It will set flag[1] = false and wait
until turn = 1. At this point, P0 will enter its critical section. A symmetric argument can be
made if turn =1.