<p>I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.</p>

<p>However, I was looking through System.Web.Security.Membership using Reflector and found code like this:</p>

<pre><code>public static class Membership
{
    private static bool s_Initialized = false;
    private static object s_lock = new object();
    private static MembershipProvider s_Provider;

    public static MembershipProvider Provider
    {
        get
        {
            Initialize();
            return s_Provider;
        }
    }

    private static void Initialize()
    {
        if (s_Initialized)
            return;

        lock(s_lock)
        {
            if (s_Initialized)
                return;

            // Perform initialization...
            s_Initialized = true;
        }
    }
}
</code></pre>

<p>Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? <strong>Are reads and writes of variables atomic?</strong> </p>

[{'answer_id': 9682, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': "<p>I thought they were - I'm not sure of the point of the lock in your example unless you're also doing something to s_Provider at the same time - then the lock would ensure that these calls happened together.</p>\n\n<p>Does that <code>//Perform initialization</code> comment cover creating s_Provider? For instance</p>\n\n<pre><code>private static void Initialize()\n{\n    if (s_Initialized)\n        return;\n\n    lock(s_lock)\n    {\n        s_Provider = new MembershipProvider ( ... )\n        s_Initialized = true;\n    }\n}\n</code></pre>\n\n<p>Otherwise that static property-get's just going to return null anyway.</p>\n"}, {'answer_id': 9689, 'author': 'John Richardson', 'author_id': 887, 'author_profile': 'https://Stackoverflow.com/users/887', 'pm_score': 2, 'selected': False, 'text': "<p>The Initialize function is faulty. It should look more like this:</p>\n\n<pre><code>private static void Initialize()\n{\n    if(s_initialized)\n        return;\n\n    lock(s_lock)\n    {\n        if(s_Initialized)\n            return;\n        s_Initialized = true;\n    }\n}\n</code></pre>\n\n<p>Without the second check inside the lock it's possible the initialisation code will be executed twice. So the first check is for performance to save you taking a lock unnecessarily, and the second check is for the case where a thread is executing the initialisation code but hasn't yet set the <code>s_Initialized</code> flag and so a second thread would pass the first check and be waiting at the lock.</p>\n"}, {'answer_id': 9699, 'author': 'olliej', 'author_id': 784, 'author_profile': 'https://Stackoverflow.com/users/784', 'pm_score': 0, 'selected': False, 'text': "<p>What you're asking is whether accessing a field in a method multiple times atomic -- to which the answer is no.</p>\n\n<p>In the example above, the initialise routine is faulty as it may result in multiple initialization.  You would need to check the <code>s_Initialized</code> flag inside the lock as well as outside, to prevent a race condition in which multiple threads read the <code>s_Initialized</code> flag before any of them actually does the initialisation code. E.g.,</p>\n\n<pre><code>private static void Initialize()\n{\n    if (s_Initialized)\n        return;\n\n    lock(s_lock)\n    {\n        if (s_Initialized)\n            return;\n        s_Provider = new MembershipProvider ( ... )\n        s_Initialized = true;\n    }\n}\n</code></pre>\n"}, {'answer_id': 9701, 'author': 'Peteter', 'author_id': 1192, 'author_profile': 'https://Stackoverflow.com/users/1192', 'pm_score': 0, 'selected': False, 'text': '<p>Perhaps <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked(VS.85).aspx" rel="nofollow noreferrer">Interlocked</a> gives a clue. And otherwise <a href="http://msdn.microsoft.com/sv-se/magazine/cc188793(en-us).aspx" rel="nofollow noreferrer">this one</a> i pretty good.</p>\n\n<p>I would have guessed that their not atomic.</p>\n'}, {'answer_id': 9711, 'author': 'John Richardson', 'author_id': 887, 'author_profile': 'https://Stackoverflow.com/users/887', 'pm_score': 1, 'selected': False, 'text': "<p>I think you're asking if <code>s_Initialized</code> could be in an unstable state when read outside the lock. The short answer is no. A simple assignment/read will boil down to a single assembly instruction which is atomic on every processor I can think of. </p>\n\n<p>I'm not sure what the case is for assignment to 64 bit variables, it depends on the processor, I would assume that it is not atomic but it probably is on modern 32 bit processors and certainly on all 64 bit processors. Assignment of complex value types will not be atomic.</p>\n"}, {'answer_id': 9712, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 1, 'selected': False, 'text': '<p>Reads and writes of variables are not atomic. You need to use Synchronisation APIs to emulate atomic reads/writes.</p>\n\n<p>For an awesome reference on this and many more issues to do with concurrency, make sure you grab a copy of Joe Duffy\'s <a href="https://rads.stackoverflow.com/amzn/click/com/032143482X" rel="nofollow noreferrer" rel="nofollow noreferrer">latest spectacle</a>. It\'s a ripper!</p>\n'}, {'answer_id': 9715, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 1, 'selected': False, 'text': '<p>"Is accessing a variable in C# an atomic operation?"</p>\n\n<p>Nope. And it\'s not a C# thing, nor is it even a .net thing, it\'s a processor thing.</p>\n\n<p>OJ is spot on that Joe Duffy is the guy to go to for this kind of info. ANd "interlocked" is a great search term to use if you\'re wanting to know more.</p>\n\n<p>"Torn reads" can occur on any value whose fields add up to more than the size of a pointer.</p>\n'}, {'answer_id': 9721, 'author': 'JoshL', 'author_id': 630, 'author_profile': 'https://Stackoverflow.com/users/630', 'pm_score': -1, 'selected': False, 'text': '<p>Ack, nevermind... as pointed out, this is indeed incorrect. It doesn\'t prevent a second thread from entering the "initialize" code section. Bah.</p>\n\n<blockquote>\n  <p>You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely.</p>\n</blockquote>\n'}, {'answer_id': 9788, 'author': 'John Richardson', 'author_id': 887, 'author_profile': 'https://Stackoverflow.com/users/887', 'pm_score': 6, 'selected': True, 'text': '<p>For the definitive answer go to the spec. :)</p>\n\n<p>Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."</p>\n\n<p>So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic.</p>\n\n<p>In particular, <code>double</code> and <code>long</code> (<code>Int64</code> and <code>UInt64</code>) are <strong>not</strong> guaranteed to be atomic on a 32-bit platform. You can use the methods on the <code>Interlocked</code> class to protect these.</p>\n\n<p>Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the <code>CompareExchange</code> and <code>Increment</code> methods.</p>\n\n<p>Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example.</p>\n'}, {'answer_id': 9792, 'author': 'John Richardson', 'author_id': 887, 'author_profile': 'https://Stackoverflow.com/users/887', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely.</p>\n</blockquote>\n\n<p>That is not correct. You will still encounter the problem of a second thread passing the check before the first thread has had a chance to to set the flag which will result in multiple executions of the initialisation code.</p>\n'}, {'answer_id': 10103, 'author': 'Rory MacLeod', 'author_id': 1016, 'author_profile': 'https://Stackoverflow.com/users/1016', 'pm_score': 3, 'selected': False, 'text': '<p>The correct answer seems to be, &quot;Yes, mostly.&quot;</p>\n<ol>\n<li>John\'s answer referencing the CLI spec indicates that accesses to variables not larger than 32 bits on a 32-bit processor are atomic.</li>\n<li>Further confirmation from the C# spec, section 5.5, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references" rel="nofollow noreferrer">Atomicity of variable references</a>:</li>\n</ol>\n<blockquote>\n<p>Reads and writes of the following data types are atomic: bool, char,\nbyte, sbyte, short, ushort, uint, int, float, and reference types. In\naddition, reads and writes of enum types with an underlying type in\nthe previous list are also atomic. Reads and writes of other types,\nincluding long, ulong, double, and decimal, as well as user-defined\ntypes, are not guaranteed to be atomic.</p>\n</blockquote>\n<ol start="3">\n<li>The code in my example was paraphrased from the Membership class, as written by the ASP.NET team themselves, so it was always safe to assume that the way it accesses the s_Initialized field is correct. Now we know why.</li>\n</ol>\n<p>Edit: As Thomas Danecker points out, even though the access of the field is atomic, s_Initialized should really be marked <em>volatile</em> to make sure that the locking isn\'t broken by the processor reordering the reads and writes.</p>\n'}, {'answer_id': 12206, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 4, 'selected': False, 'text': '<p>Hang about -- the question that is in the title is definitely not the real question that Rory is asking.</p>\n\n<p>The titular question has the simple answer of "No" -- but this is no help at all, when you see the real question -- which i don\'t think anyone has given a simple answer to.</p>\n\n<p>The real question Rory asks is presented much later and is more pertinent to the example he gives.</p>\n\n<blockquote>\n  <p>Why is the s_Initialized field read\n  outside of the lock?</p>\n</blockquote>\n\n<p>The answer to this is also simple, though completely unrelated to the atomicity of variable access.</p>\n\n<p>The s_Initialized field is read outside of the lock because <strong>locks are expensive</strong>.</p>\n\n<p>Since the s_Initialized field is essentially "write once" it will never return a false positive.</p>\n\n<p>It\'s economical to read it outside the lock.</p>\n\n<p>This is a <em>low cost</em> activity with a <em>high</em> chance of having a benefit.</p>\n\n<p>That\'s why it\'s read outside of the lock -- to avoid paying the cost of using a lock unless it\'s indicated.</p>\n\n<p>If locks were cheap the code would be simpler, and omit that first check.</p>\n\n<p><em>(edit: nice response from rory follows. Yeh, boolean reads are very much atomic. If someone built a processor with non-atomic boolean reads, they\'d be featured on the DailyWTF.)</em></p>\n'}, {'answer_id': 73827, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 5, 'selected': False, 'text': '<p>This is a (bad) form of the double check locking pattern which is <strong>not</strong> thread safe in C#!</p>\n\n<p>There is one big problem in this code:</p>\n\n<p>s_Initialized is not volatile. That means that writes in the initialization code can move after s_Initialized is set to true and other threads can see uninitialized code even if s_Initialized is true for them. This doesn\'t apply to Microsoft\'s implementation of the Framework because every write is a volatile write.</p>\n\n<p>But also in Microsoft\'s implementation, reads of the uninitialized data can be reordered (i.e. prefetched by the cpu), so if s_Initialized is true, reading the data that should be initialized can result in reading old, uninitialized data because of cache-hits (ie. the reads are reordered).</p>\n\n<p>For example:  </p>\n\n<pre><code>Thread 1 reads s_Provider (which is null)  \nThread 2 initializes the data  \nThread 2 sets s\\_Initialized to true  \nThread 1 reads s\\_Initialized (which is true now)  \nThread 1 uses the previously read Provider and gets a NullReferenceException\n</code></pre>\n\n<p>Moving the read of s_Provider before the read of s_Initialized is perfectly legal because there is no volatile read anywhere.</p>\n\n<p>If s_Initialized would be volatile, the read of s_Provider would not be allowed to move before the read of s_Initialized and also the initialization of the Provider is not allowed to move after s_Initialized is set to true and everything is ok now.</p>\n\n<p>Joe Duffy also wrote an Article about this problem: <a href="http://joeduffyblog.com/2006/01/26/broken-variants-on-doublechecked-locking/" rel="nofollow noreferrer">Broken variants on double-checked locking</a></p>\n'}, {'answer_id': 12206783, 'author': 'doug65536', 'author_id': 1127972, 'author_profile': 'https://Stackoverflow.com/users/1127972', 'pm_score': 0, 'selected': False, 'text': "<p>To make your code always work on weakly ordered architectures, you must put a MemoryBarrier before you write s_Initialized.</p>\n\n<pre><code>s_Provider = new MemershipProvider;\n\n// MUST PUT BARRIER HERE to make sure the memory writes from the assignment\n// and the constructor have been wriitten to memory\n// BEFORE the write to s_Initialized!\nThread.MemoryBarrier();\n\n// Now that we've guaranteed that the writes above\n// will be globally first, set the flag\ns_Initialized = true;\n</code></pre>\n\n<p>The memory writes that happen in the MembershipProvider constructor and the write to s_Provider are not guaranteed to happen before you write to s_Initialized on a weakly ordered processor.</p>\n\n<p>A lot of thought in this thread is about whether something is atomic or not. That is not the issue. The issue is <strong>the order that your thread's writes are visible to other threads</strong>. On weakly ordered architectures, writes to memory do not occur in order and THAT is the real issue, not whether a variable fits within the data bus.</p>\n\n<p><strong>EDIT:</strong> Actually, I'm mixing platforms in my statements. In C# the CLR spec requires that writes are globally visible, in-order (by using expensive store instructions for every store if necessary). Therefore, you don't need to actually have that memory barrier there. However, if it were C or C++ where no such guarantee of global visibility order exists, and your target platform may have weakly ordered memory, and it is multithreaded, then you would need to ensure that the constructors writes are globally visible before you update s_Initialized, which is tested outside the lock.</p>\n"}, {'answer_id': 15125936, 'author': 'James Anderson', 'author_id': 38207, 'author_profile': 'https://Stackoverflow.com/users/38207', 'pm_score': 1, 'selected': False, 'text': '<p>An <code>If (itisso) {</code> check on a boolean is atomic, but even if it was not\nthere is no need to lock the first check.</p>\n\n<p>If any thread has completed the Initialization then it will be true. It does not matter if several threads are checking at once. They will all get the same answer, and, there will be no conflict.</p>\n\n<p>The second check inside the lock is necessary because another thread may have grabbed the lock first and completed the initialization process already.</p>\n'}]
['https://Stackoverflow.com/questions/9666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016/']