Note that there are some explanatory texts on larger screens.

plurals
  1. POIs the volatile keyword required for this double checked lock to work?
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1964731/the-need-for-volatile-modifier-in-double-checked-locking-in-net">The need for volatile modifier in double checked locking in .NET</a> </p> </blockquote> <p>Given the following code snippet, which can be executed by more than one thread at once, would the volatile keyword be required to ensure that the 'real value' of <code>connected</code> is always read from the memory and not a cache?</p> <p>(Assume that <code>Disconnect()</code> will only be called once (i.e. if it doesn't work properly the first time and the value of <code>connected</code> is read as false, it's not going to be attempted again)).</p> <pre><code>public class MyClass { private readonly object syncRoot = new object(); private bool connected; public void Disconnect() { if (connected) { lock (syncRoot) { if (connected) { // log off here // ... connected = false; } } } } public void Connect() { lock (syncRoot) { // blah // blah connected = true; } } } </code></pre> <p>My feeling is that if double checked locking is used then it does need to be marked volatile since if it reads the incorrect value the first time, then it's going to think it's actually disconnected and won't go into the lock statement. I also think that in this case double checked locking isn't appropriate / isn't going to provide any performance gain and just a normal lock would do the job.</p> <p>I'd like someone to confirm or deny these thoughts.</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