Reputation: 24067
MSDN states that:
Reads and writes of other types, including
long
,ulong
,double
, anddecimal
, as well as user-defined types, need not be atomic.
C# 7.0 draft specification - Variables - 9.6 Atomicity of variable references
Will Volatile.Write(Double, Double)
work as atomic operation? If so how this is guaranteed?
Is it safe to do Volatile.Write(ref mydouble, value);
in one thread and Volatile.Read(ref mydouble)
in another where mydouble
has double
type?
That was general question. Another question - what should I do in this particular situation:
Upvotes: 11
Views: 1161
Reputation: 74654
No, Volatile
is not atomic, and it is not safe in an SMP (>1 processor) system to assume so. It is safe on a uniprocessor machine.
Unless you really need the performance, you probably want Interlocked
instead, either Interlocked.Exchange
or Interlocked.Read
.
Upvotes: 8
Reputation: 1440
As of 2023, the documentation (and/or implementation) of the Volatile
class have since been updated, stating now:
The Volatile class also provides read and write operations for some 64-bit types such as Int64 and Double. Volatile reads and writes on such 64-bit memory are atomic even on 32-bit processors, unlike regular reads and writes.
So Volatile.Read
and Volatile.Write
on 64 bit values are in fact atomic, even on 32 bit systems.
However, note that reads and writes performed with the Volatile
class are not the same as reads/writes using volatile
fields. So accessing 64 bit volatile
fields is not atomic, while using the Volatile
class is atomic.
From the volatile
(keyword) documentation:
Other types, including double and long, cannot be marked volatile because reads and writes to fields of those types cannot be guaranteed to be atomic. To protect multi-threaded access to those types of fields, use the Interlocked class members or protect access using the lock statement.
Interestingly enough, the Volatile
class isn't mentioned here for atomic access, I would personally say that this part of the documentation is a bit outdated.
Upvotes: 1