Search code examples
multithreadinglogicrace-conditionpseudocode

Where is the race condition?


I had a question on a test recently that basically said to make 3 concurrent processes execute some block of code in order.


Example of execution order incase that did not make sense:

P1 P2 P3 P1 P2 P3 ...

For my answer I wrote this pseudo-ish code

shared s[2] = {-1,-1};
void Process1(){
   while(1){
      if(s[0] < 0 && s[1] < 0){
         DO_CS;
         s[0] = 1;
      }
   }
}

void Process2(){
   while(1){
      if(s[0] > 0 && s[1] < 0){
         DO_CS;
         s[1] = 1;
      }
   }
}

void Process3(){
   int i = 0;
   while(1){
      if(s[1] > 0 && s[0] > 0){
         DO_CS;
         s[0] = -1;
         s[1] = -1;
      }
  }
}

My teacher wrote race condition and circled the last line in the if statement on Process3 and drew an arrow to the conditional statement in process2.

I am having trouble seeing how this could cause a race condition. I am sure it is obvious but I just can't see it.

Thanks!


Solution

  • Consider the following order of events:

    1. After some time, s = [1, 1].
    2. Within Process2, the thread is in the midst of evaluating the expression in the if statement, and just passed the truthy condition s[0] > 0 and is about to continue.
    3. Within Process3, you modify s to be [-1, -1].
    4. Process2 evaluates the rest of the expression and goes into action before Process1.