title: Threads synchronization. How exactly lock makes access to memory 'correct'?
body: <p>First of all, I know that <code>lock{}</code> is synthetic sugar for <code>Monitor</code> class. (oh, <strong>syntactic</strong> sugar)</p>
  
  <p>I was playing with simple multithreading problems and discovered that cannot totally understand how lockng some arbitrary WORD of memory secures whole other memory from being cached is registers/CPU cache etc. It's easier to use code samples to explain what I'm saying about:</p>
  
  <pre><code>for (int i = 0; i &lt; 100 * 1000 * 1000; ++i) {
      ms_Sum += 1;
  }
  </code></pre>
  
  <p>In the end <code>ms_Sum</code> will contain <code>100000000</code> which is, of course, expected.</p>
  
  <p>Now we age going to execute same cycle but on 2 different threads and with upper limit halved.</p>
  
  <pre><code>for (int i = 0; i &lt; 50 * 1000 * 1000; ++i) {
      ms_Sum += 1;
  }
  </code></pre>
  
  <p>Because of no synchronization we get incorrect result - on my 4-core machine it is random number nearly <code>52 388 219</code> which is slightly larger than half from <code>100 000 000</code>. If we enclose <code>ms_Sum += 1;</code> in <code>lock {}</code>, we, of cause, would get absolutely correct result <code>100 000 000</code>. But what's interesting for me (truly saying I <strong>was</strong> expecting alike behavior) that adding <code>lock</code> before of after <code>ms_Sum += 1;</code> line makes answer <strong>almost</strong> correct:</p>
  
  <pre><code>for (int i = 0; i &lt; 50 * 1000 * 1000; ++i) {
      lock (ms_Lock) {}; // Note curly brackets
  
      ms_Sum += 1;
  }
  </code></pre>
  
  <p>For this case I usually get <code>ms_Sum = 99 999 920</code>, which is very close.</p>
  
  <p><strong>Question:</strong> why exactly <code>lock(ms_Lock) { ms_Counter += 1; }</code> makes program completely correct but <code>lock(ms_Lock) {}; ms_Counter += 1;</code> only <em>almost</em> correct; how locking arbitrary <code>ms_Lock</code> variable makes <strong>whole memory</strong> stable?</p>
  
  <p>Thanks a lot!</p>
  
  <p><em>P.S. Gone to read books about multithreading.</em></p>
  
  <p><strong>SIMILAR QUESTION(S)</strong></p>
  
  <p><a href="https://stackoverflow.com/questions/5996371/how-does-the-lock-statement-ensure-intra-processor-synchronization">How does the lock statement ensure intra processor synchronization?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/7264841/thread-synchronization-why-exactly-this-lock-isnt-enough-to-synchronize-threads">Thread synchronization. Why exactly this lock isn&#39;t enough to synchronize threads</a></p>