Search code examples
clockingwhile-looprace-conditioncritical-section

preventing race conditions by using strict alteration


I found the following code in a book about operating systems. It is a technique called "strict alteration" that is supposed to prevent race conditions between processes by using a lock when a process enters a critical region. I understand race conditions, but I don't quite understand this code.

// process 0
while(TRUE) {
   while(turn != 0)   /* loop */
   critical_region();
   turn = 1;
   noncritical_region();
}

There is also this code that is right next to it.

// process 1
while(TRUE) {
   while(turn != 1)   /* loop */
   critical_region();
   turn = 0;
   noncritical_region();
}

I think there might by a typo in this code for the second while loop. If there isn't, then can someone explain how this code works? The explanation in the book didn't make sense to me. It only makes sense on a very general, abstract level. However when I look at this code I just don't get it.


Solution

  • Well, the turn variable contains the number of the process that's allowed to enter the critical section. Hopefully it does some useful work here, then it explicitly allows the other process to enter the critical section by changing the turn variable. As a result, the processes each take a turn doing work, repeatedly.

    This comes to a screeching halt when one of the process terminates. It will be given the turn by the live process but never gives the turn back because it doesn't run anymore. The live process won't be doing any useful work.