15

Update: I just stumbled upon this in Eric Lippert's answer to another question (he is quoting the spec):

Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

OK, so reading a double is not atomic. This means the value could get modified mid-read, right? So how does one read a double value atomically?


I notice there's an Interlocked.Read method for long values. This makes sense to me, as reading a 64-bit value must require two steps and therefore be subject to race conditions just like every other non-atomic action.

But there's no Interlocked.Read for double values, even though System.Double is a 64-bit value.

I am seeing some strange behavior in my program where my GUI, which displays a double in a text box while that double is also being frequently updated by other threads, is showing the correct value (in the vicinity of 200.0) most of the time, and then randomly showing an erroneous value (like -0.08) occasionally.

Maybe this is a threading issue, or maybe it's something else. But first off I wanted to narrow down the possiblities. So: is reading a double thread-safe?

Community
  • 1
  • 1
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • Keep in mind that even if reading is atomic, it won't help you if writing isn't. – nos Sep 09 '10 at 13:16
  • @nos: Right. But it's strange because the `Interlocked` class *does* provide atomic write operations: `Exchange` and `CompareExchange` both accept `double` arguments. – Dan Tao Sep 09 '10 at 13:20
  • 3
    @Dan, in response to the follow-up question in your edit, see Jon Skeet's [answer to another question here](http://stackoverflow.com/questions/531759/c-volatile-double/531772#531772), in which he suggests using `BitConverter` to move between long and double (in conjunction with `Interlocked.Read`). – Jeff Sternal Sep 09 '10 at 13:20
  • @Jeff: Nice, I will check that out. – Dan Tao Sep 09 '10 at 13:20
  • @Jeff: nice and clever hack, however what's the benefit of giving complexity to a problem that can be solved with a simple mutex? – CharlesB Sep 09 '10 at 13:29
  • @CharlesB, I think the point is just speed, though it's not clear whether the additional operations would negate the benefits of not locking. – Jeff Sternal Sep 09 '10 at 13:35
  • 1
    @Jeff: Locks are pretty fast *if they are not contended*. And if they are contended then clearly you have larger problems to deal with; best to fix whatever architectural issue is causing the contention than to live dangerously with low-lock techniques that are easy to get wrong. – Eric Lippert Sep 09 '10 at 14:13
  • A general comment - for your app does it matter if it is not thread safe for your GUI to read the value? If the other threads are writing valid values all the time then is it the case that the worst that will happen is your display is slightly out of date for 1 second (or whatever is your read interval) because it read one byte wrong - do you care? For the actual symptom you have described above (and I know this is not strictly what your question is asking) it looks more like the issue is that one of the other threads is writing something odd (and this might be a place to look at locks etc). – Mick Sep 09 '10 at 14:33
  • 1
    @Mick - it sounds like the problem isn't stale data, but torn reads (where you see data where only 4 of the 8 bytes of the double have been updated). – kvb Sep 09 '10 at 14:57
  • Well, getting the spec quoted back at you is sort of an answer. From the Microsoft-dude-that-posts-at-SO, no less. If that works for you, have at it. The red pill is certainly less comfortable. – Hans Passant Sep 09 '10 at 23:52
  • It's also worth noting this answer. On a 64 bit processor, operations on 64 bit types are atomic if it's built for x64. https://stackoverflow.com/a/24731936/654070 – Will Calderwood Jul 07 '21 at 13:02

4 Answers4

19

is reading a double thread-safe?

No. As the spec says

Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

Moving on.

This means the value could get modified mid-read, right?

Yes.

So how does one read a double value atomically?

You take a lock out around every access to the mutable variable.

And a question you didn't ask, but often gets asked as a follow-up to your questions:

Does making a field "volatile" make reads/writes of it atomic?

No. It is not legal to make a volatile field of type double.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
9

The usual way: control access with a lock.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • Basically, this seems to be the most sensible answer (and came first, though Eric's is also quite informative). I am intrigued by the possibility of other, more adventurous, approaches; but I will pursue those on my own time and accept this is the reasonable thing to do in nearly all cases. – Dan Tao Oct 11 '10 at 12:47
8

Use Interlocked.Exchange OR Interlocked.CompareExchange for atomic read like this.

Interlocked.Exchange(ref somevariable, somevariable)

It returns original value.

If you want to avoid writing use compareExchange.

Interlocked.CompareExchange(ref somevariable, somevalue, somevalue);

This will replace the variable with the second argument if it is equal to the third argument, and return the original value. By using the same value (e.g., zero) in both spots it guarantees that the value of the variable is not changed.

pavy bez
  • 81
  • 1
  • 1
2

The CLR only promises a variable alignment of 4. Which means that it is quite possible for a long or double to straddle the boundaries of a CPU cache-line. That makes the read guaranteed to be non-atomic.

It is also a fairly serious perf problem, reading such a poorly aligned variable is over 3 times as slow. Nothing you can really do about it beyond hacking pointers.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    If there is a cache miss on the x86 fld instruction, I'm not sure if the CPU will allow a partial load to the FPU register. My guess is that the CPU itself will do some interlocking to preserve atomicity of FPU operations. I haven't found Intel docs to either prove or disprove this. Still, even if Intel CPUs do this, others may not. – Dan Bryant Sep 10 '10 at 00:27