开发者

Is reading a double not thread-safe?

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开发者_JAVA技巧 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?


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.


The usual way: control access with a lock.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜