Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Volatile.Read / Volatile.Write for "double" atomic?

Tags:

c#

.net-4.5

MSDN states that

long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic 5.5 Atomicity of variable references

Will Volatile.Write Method (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:

  • 2 processors Xeon x64 server
  • Windows + MS .NET 4.5
  • read/write double from different threads
  • SMALLEST latency (need smallest because i'm writing HFT software)
like image 909
Oleg Vazhnev Avatar asked Sep 15 '12 07:09

Oleg Vazhnev


1 Answers

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.

like image 97
Ana Betts Avatar answered Sep 21 '22 11:09

Ana Betts