title: Possible value of Variable when given two threads are running parallely?
body: <p>The problem is from question paper at <a href="https://web.stanford.edu/~ouster/cgi-bin/cs140-winter13/downloads/Midterm%20(Winter%202012).pdf" rel="noreferrer">Stanford.</a> The description of it is as follows:</p>
  
  <p>Suppose two threads execute the following C code concurrently, accessing shared variables a, b,
  and c:</p>
  
  <p><b>Initialization</b><br></p>
  
  <pre><code>int a = 4;
  int b = 0;
  int c = 0;
  </code></pre>
  
  <p><b>Thread 1:</b><br></p>
  
  <pre><code>if (a &lt; 0) { 
   c = b - a;
  } else {
   c = b + a;
  }
  </code></pre>
  
  <p><b>Thread 2:</b><br></p>
  
  <pre><code>b = 10;
  a = -3
  </code></pre>
  
  <p>What are the possible values for <code>c</code> after both threads complete? You can assume that reads and
  writes of the variables are atomic, and that the order of statements within each thread is preserved in the code generated by the C compiler.</p>
  
  <p><b>Answer : 4,7,14,13,-3</b></p>
  
  <p>I understood the first four outputs as follows, but I'm not able to understand how the output -3 can occur given that order of statements within the thread is preserved.</p>
  
  <p><b>4</b>: Execute thread 1 completely, then execute thread 2.<br>
  <b>7</b>: Interrupt thread 1 before <code>c = b + a</code>, and then execute thread 2, followed by executing thread 1 again. <br>
  <b>14</b>: Execute thread 2 till <code>b = 10</code> is done, then interrupt it, and execute thread 1 completely. <br>
  <b>13</b>: Execute thread 2 completely, then thread 1.</p>
  
  <p>Now I'm stuck on how to obtain -3 as a final value of <code>c</code>? -3 is only possible when <code>b=0</code>, and <code>a=-3</code>, and thread 1 starts its execution from <code>c = b + a</code>. I don't see -3 to be possible in any other case. But as mentioned in question, order of statements is maintained, so the value of a can not be -3, unless we change the value of b to 10. </p>
  
  <p>Can someone explain how the output -3 is possible in this case?</p>