title: what's the possible result of the following code in concurrency situation?
body: <p>I have seen an interview question as below:
  What's the possible range of the result of the following code:</p>
  
  <pre><code>void ThreadProc(int&amp; sum)
  {
      for (int i = 1; i &lt;= 50; i++)
      {
          sum += 1;
      }
  }
  
  int main()
  {
      int sum = 0;
      thread t1(ThreadProc, std::ref(sum));
      thread t2(ThreadProc, std::ref(sum));
      t1.join();
      t2.join();
      cout &lt;&lt; sum &lt;&lt; '\n';
      return 0;
  }
  </code></pre>
  
  <p>The given answer is <strong>[50,100]</strong>.
  However, I thought it should be <strong>[2,100]</strong>.
  If given sequence as below, <code>sum</code> will be <strong>2</strong>.</p>
  
  <ol>
  <li>thread <code>t1</code> get the cpu, and load the initial <code>sum=0</code> into cache (let's say the cached sum is <code>c1</code>, its value is <code>0</code> now).</li>
  <li>thread <code>t2</code> get the cpu, and increase (49 times), and now the sum will be 49.</li>
  <li>thread <code>t1</code> get the cpu, and compute <code>sum = c1 + 1</code>, now <code>sum</code> is <code>1</code>.</li>
  <li>thread <code>t2</code> get the cpu, and load the <code>sum</code> (<code>=1</code>) and compute <code>sum + 1</code> and cached the result (<code>c1</code> is <code>2</code> now). Before the <code>c1</code> is written to variable <code>sum</code> by <code>t1</code>, <code>t2</code> preempt the cpu.</li>
  <li>thread <code>t2</code> get the cpu, and increase (1 times) [and now the <code>sum</code> will be <code>x</code> (the value does't matter)], then <code>thread t2</code> finished.</li>
  <li><p>thread <code>t1</code> get the cpu, and write the cached result <code>c1</code> to sum,
  now <code>sum</code> is <code>2</code>.</p>
  
  <p><strong>Am I right?</strong></p></li>
  </ol>