Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Having only 1 thread lock accomplishes nothing. The purpose of the lock is to block <em>other</em> threads, but it doesn't work if no one else checks the lock!</p> <p>Now, you don't need to worry about memory corruption with a 32-bit int, because the <em>write</em> is atomic - but that doesn't necessarily mean you can go lock-free.</p> <p>In your example, it is possible to get questionable semantics:</p> <pre><code>example = 10 Thread A: Add(10) read example (10) Thread B: Read() read example (10) Thread A: write example (10 + 10) </code></pre> <p>which means ThreadB started to read the value of example <em>after</em> thread A began it's update - but read the preupdated value. Whether that's a problem or not depends on what this code is supposed to do, I suppose.</p> <p>Since this is example code, it may be hard to see the problem there. But, imagine the canonical counter function:</p> <pre><code> class Counter { static int nextValue = 0; static IEnumerable&lt;int&gt; GetValues(int count) { var r = Enumerable.Range(nextValue, count); nextValue += count; return r; } } </code></pre> <p>Then, the following scenario:</p> <pre><code> nextValue = 9; Thread A: GetValues(10) r = Enumerable.Range(9, 10) Thread B: GetValues(5) r = Enumerable.Range(9, 5) nextValue += 5 (now equals 14) Thread A: nextValue += 10 (now equals 24) </code></pre> <p>The nextValue is incremented properly, but the ranges returned will overlap. The values of 19 - 24 were never returned. You would fix this by locking around the var r and nextValue assignment to prevent any other thread from executing at the same time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload