Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, you don't need <em>locks</em> necessarily - but if you want one thread to definitely read the value that another thread has written, you either need locks or a volatile variable.</p> <p>I've personally given up trying to understand the precise meaning of volatile. I try to avoid writing my own lock-free code, instead relying on experts who really understand the memory model.</p> <p>EDIT: As an example of the kind of problem this can cause, consider this code:</p> <pre><code>using System; using System.Threading; public class Test { private static bool stop = false; private bool Stop { get { return stop; } set { stop = value; } } private static void Main() { Thread t = new Thread(DoWork); t.Start(); Thread.Sleep(1000); // Let it get started Console.WriteLine("Setting stop flag"); Stop = true; Console.WriteLine("Set"); t.Join(); } private static void DoWork() { Console.WriteLine("Tight looping..."); while (!Stop) { } Console.WriteLine("Done."); } } </code></pre> <p>That program <em>may or may not</em> terminate. I've seen both happen. There's no guarantee that the "reading" thread will <em>actually</em> read from main memory - it can put the initial value of <code>stop</code> into a register and just keep using that forever. I've seen that happen, in reality. It doesn't happen on my current machines, but it may do on my next.</p> <p>Putting locks within the property getter/setter as per the code in the question would make this code correct and its behaviour predictable.</p> <p>For more on this, see this <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three.aspx" rel="noreferrer">blog post by Eric Lippert</a>.</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