3

Why is there no Interlocked.Read function available for double since there are Interlocked.Exchange and Interlocked.CompareExchange methods available for double which can perform more complex functions atomically. Using such methods to read a double value atomically (instead of using Interlocked.Read) will add an overhead to a simple reading operation.

Could you suggest a simpler approach to read a double atomically where as another thread is updating this double using Interlocked.Exchange method.

Alok
  • 3,160
  • 3
  • 28
  • 47
  • if "another thread is updating this double" what value do you expect to retrieve? old value or new value? – Mitch Wheat Jul 14 '14 at 03:27
  • @MitchWheat, doesn't other thread's update operation should be blocked until current thread's read operation is performed? – Tony Jul 14 '14 at 03:38
  • want to read new value. – Alok Jul 14 '14 at 03:39
  • @Tony: poster appears to be asking for something fast. On re-read I have no idea what they are asking! --> "...will add an overhead to a simple reading operation" - Yes, locking involves an overhead... – Mitch Wheat Jul 14 '14 at 03:42
  • @MitchWheat sorry for confusion in the question. I meant an overhead compared to Interlocked.Read operation. I am creating a temp variable and using Interlocked.Exchange to read the double atomically and return the temp value. A simple Interlocked.Read seems much simpler than Interlocked.Exchange method. Any thoughts? – Alok Jul 14 '14 at 03:46
  • Is it causing a bottleneck? If not, move on with something more important.... – Mitch Wheat Jul 14 '14 at 03:47
  • not the bottleneck, but I am more interested in correctness. What I wanted to know is that when a thread is updating a double value using Interlocked.Exchange, other thread cannot just read the double normally without losing atomicity. It has to store the value into a temp double using Interlocked.Exchange and use the temp value. – Alok Jul 14 '14 at 04:53

1 Answers1

0

Interlocked.Read for long is implemented like this:

return Interlocked.CompareExchange(ref location,0,0);

That means that using CompareExchange instead of Read does not add an overhead, not for long and not for double.

Martin
  • 1,986
  • 15
  • 32