title: Is accessing a variable in C# an atomic operation?
body: <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>