# Critical-Section Problem. (Dekker)

Peon666
I read this code in my OS book but I'm having trouble understanding it. Would someone explain to me what's happening in this code? This code is the first-known correct software solution to the critical-section problem for two processes and was developed by Dekker.

Code:
boolean flag[2];
int turn;

// Above two variables are shared by the two processes.

do {
flag[i]=TRUE;
while (flag[j]){
if (turn == j){
while (turn == j)
;// do nothing
flag[i]=FALSE;
}
}

// critical section

turn = j;
flag[i]=FALSE;

// remainder section.

}while (TRUE);

I'm totally clueless about what's going on in this code.

## Answers and Replies

Homework Helper
The example you show isn't quite right, wiki shows the proper version:

http://en.wikipedia.org/wiki/Dekker's_algorithm

This matches the wiki version:

Code:
volatile boolean flag[2] = {FALSE, FALSE}  // global shared variable
volatile int turn = 0;                     // global shared variable

static int i, j;

// initialize
// for process 0, i = 0, j = 1
// for process 1, i = 1, j = 0

do{

// non-critical section

flag[i] = TRUE;              // set flag[i] to request ownership
while(flag[j] == TRUE){      // while other process has set flag[j]
if(turn != i){           //   if turn != this process
flag[i] = FALSE;    //     clear flag[i] so other process can run
while(turn != i);   //     wait for other process to change turn
flag[i] = TRUE;     //     set flag[i] to request ownership
}
}                            // wait until other process clears flag[j]

// critical section

turn = j;                    // set turn to other process
flag[i] = FALSE;             // clear flag[i] so other process can run

// non-critical section

}while (TRUE);

Last edited: