First of all, I know that `lock{}` is synthetic sugar for `Monitor` class. (oh, **syntactic** sugar)

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:

```
for (int i = 0; i < 100 * 1000 * 1000; ++i) {
    ms_Sum += 1;
}

```

In the end `ms_Sum` will contain `100000000` which is, of course, expected.

Now we age going to execute same cycle but on 2 different threads and with upper limit halved.

```
for (int i = 0; i < 50 * 1000 * 1000; ++i) {
    ms_Sum += 1;
}

```

Because of no synchronization we get incorrect result - on my 4-core machine it is random number nearly `52 388 219` which is slightly larger than half from `100 000 000`. If we enclose `ms_Sum += 1;` in `lock {}`, we, of cause, would get absolutely correct result `100 000 000`. But what's interesting for me (truly saying I **was** expecting alike behavior) that adding `lock` before of after `ms_Sum += 1;` line makes answer **almost** correct:

```
for (int i = 0; i < 50 * 1000 * 1000; ++i) {
    lock (ms_Lock) {}; // Note curly brackets

    ms_Sum += 1;
}

```

For this case I usually get `ms_Sum = 99 999 920`, which is very close.

**Question:** why exactly `lock(ms_Lock) { ms_Counter += 1; }` makes program completely correct but `lock(ms_Lock) {}; ms_Counter += 1;` only *almost* correct; how locking arbitrary `ms_Lock` variable makes **whole memory** stable?

Thanks a lot!

*P.S. Gone to read books about multithreading.*

**SIMILAR QUESTION(S)**

[How does the lock statement ensure intra processor synchronization?](https://stackoverflow.com/questions/5996371/how-does-the-lock-statement-ensure-intra-processor-synchronization)

[Thread synchronization. Why exactly this lock isn't enough to synchronize threads](https://stackoverflow.com/questions/7264841/thread-synchronization-why-exactly-this-lock-isnt-enough-to-synchronize-threads)