Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Critical-Section Problem. (Dekker)

  1. Apr 6, 2010 #1
    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 (Text):

    boolean flag[2];
    int turn;

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

    do {
        while (flag[j]){
            if (turn == j){
                while (turn == j)
                   ;// do nothing

    // critical section

    turn = j;

    // remainder section.

    }while (TRUE);

    I'm totally clueless about what's going on in this code.
  2. jcsd
  3. Apr 6, 2010 #2


    User Avatar
    Homework Helper

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


    This matches the wiki version:

    Code (Text):

    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


    // 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: Apr 6, 2010
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook