0

Take this program as an example:

class Program
{
   public static double myVar1 = 0;
   public static double myVar2 = 0;

   static void Main()
   {
      Thread thread1 = new Thread(new ThreadStart(update_variable));
      thread1.Start();

      while (true)
      {
         myVar2 = myVar1;
      }
   }

   static update_variable()
   {
      while (true)
      {
         myVar1 = 2222222.22;
         myVar1 = 1111111.11;
      }
   }
}

Would it ever be possible for myVar2 to equal a value other than 222222.22 or 1111111.11? In other words, are the bytes for a variable changed "all or nothing" or could the main thread see myVar1 at a instance in time when some of the bytes have changed and others have not, giving an unexpected value?

I've tested the above program and do NOT see that behavior, but wondering if it's possible and if this would be considered thread safe code. I would prefer to not use the resources of a lock since I have only one thread that changes the data and one that uses the data.

Fildor
  • 14,510
  • 4
  • 35
  • 67
MikeD
  • 171
  • 2
  • 13
  • 2
    [Specification](https://github.com/dotnet/csharplang/blob/master/spec/variables.md#atomicity-of-variable-references): Reads and writes of other types, including `long`, `ulong`, **`double`**, and `decimal`, as well as user-defined types, are not guaranteed to be atomic. – user4003407 Oct 15 '18 at 05:21

1 Answers1

2

To answer your question, yes, it is possible; some of the bytes in the double may be updated when the other thread reads the value, so will contain corrupt data.

If you are interested in ways to read and write atomically but without using lock, I suggest you look at the Interlocked class which supports a limited set of atomic operations.

See also c# interlocked methods as a locking mechanism?.

John Wu
  • 50,556
  • 8
  • 44
  • 80