title: Simulate tearing a double in C#
body: <p>I'm running on a 32-bit machine and I'm able to confirm that long values can tear using the following code snippet which hits very quickly.</p>
  
  <pre><code>        static void TestTearingLong()
          {
              System.Threading.Thread A = new System.Threading.Thread(ThreadA);
              A.Start();
  
              System.Threading.Thread B = new System.Threading.Thread(ThreadB);
              B.Start();
          }
  
          static ulong s_x;
  
          static void ThreadA()
          {
              int i = 0;
              while (true)
              {
                  s_x = (i &amp; 1) == 0 ? 0x0L : 0xaaaabbbbccccddddL;
                  i++;
              }
          }
  
          static void ThreadB()
          {
              while (true)
              {
                  ulong x = s_x;
                  Debug.Assert(x == 0x0L || x == 0xaaaabbbbccccddddL);
              }
          }
  </code></pre>
  
  <p>But when I try something similar with doubles, I'm not able to get any tearing.  Does anyone know why?  As far as I can tell from the spec, only assignment to a float is atomic.  The assignment to a double should have a risk of tearing.</p>
  
  <pre><code>    static double s_x;
  
      static void TestTearingDouble()
      {
          System.Threading.Thread A = new System.Threading.Thread(ThreadA);
          A.Start();
  
          System.Threading.Thread B = new System.Threading.Thread(ThreadB);
          B.Start();
      }
  
      static void ThreadA()
      {
          long i = 0;
  
          while (true)
          {
              s_x = ((i &amp; 1) == 0) ? 0.0 : double.MaxValue;
              i++;
  
              if (i % 10000000 == 0)
              {
                  Console.Out.WriteLine("i = " + i);
              }
          }
      }
  
      static void ThreadB()
      {
          while (true)
          {
              double x = s_x;
  
              System.Diagnostics.Debug.Assert(x == 0.0 || x == double.MaxValue);
          }
      }
  </code></pre>