36

I was unable to find any reference to this in the documentations...

Is assigning to a double (or any other simple type, including boolean) an atomic operation viewed from the perspective of threads?

double value = 0;

public void First() {
 while(true) {
  value = (new Random()).NextDouble();
 }
}

public void Second() {
 while(true) {
  Console.WriteLine(value);
 }
}

In this code sample, first method is called in one thread, and the second in another. Can the second method get a messed up value if it gets its execution during assignment to the variable in another thread?

I don't care if I receive the old value, it's only important to receive a valid value (not one where 2 out of 8 bytes are set). I know it's a stupid question, but I want to be sure, cause I don't know how CLR actually sets the variables.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
AStrangerGuy
  • 361
  • 3
  • 3
  • 29
    This is not a stupid question. – Eric Lippert Apr 29 '10 at 14:17
  • @EricLippert Object a = 10; it this an atomic operation as well? i have read MSDN, your articles etc. But can't seem to find answer to it. as it involves 2 steps. boxing and then assignment – Ehsan Aug 23 '13 at 07:25
  • @NoOne: The mutation of variable `a` is atomic because `object` is a reference type. The boxing doesn't come into it. – Eric Lippert Aug 23 '13 at 13:48

1 Answers1

24

To answer your question, no. Assignments to doubles are not guarenteed to be atomic. The docs are available here. Basically, <= 32-bit built-in types are atomic, >= 64-bit types aren't. For atomic operations on 64bit types, you can use the methods on System.Threading.Interlocked

thecoop
  • 45,220
  • 19
  • 132
  • 189