正在读双不是线程安全的? [英] 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):
读取和其他类型的读写, 包括长,ULONG,双,和 小数,以及用户定义 类型,不能保证是 原子。
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?
我注意到有一个<一个href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.read.aspx"><$c$c>Interlocked.Read$c$c>方法长
值。这对我来说很有意义,因为读一个64位的值必须需要两个步骤,因此受到竞争条件就像所有其他的非原子操作。
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.
但是没有 Interlocked.Read
为双
值,即使 System.Double
是一个64位的值。
But there's no Interlocked.Read
for double
values, even though System.Double
is a 64-bit value.
我看到在我的计划一些奇怪的行为在我的图形用户界面,它显示一个双
在文本框中而双
也被经常被其它线程更新,则表示正确的值(在200.0附近)的最的的时间,然后随机示出一个错误值(像-0.08)的偶尔的。
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.
也许这是一个线程问题,也可能是别的东西。但首先,我想缩小possiblities。所以:正在读双
线程安全的。
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?
推荐答案
通常的方法:用一把锁控制访问
The usual way: control access with a lock.
这篇关于正在读双不是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!