阅读双线不是线程安全的? [英] Is reading a double not thread-safe?
问题描述
更新:我刚刚在 Eric Lippert的回答 另一个问题(他引用规范):
Update: I just stumbled upon this in Eric Lippert's answer to another question (he is quoting the spec):
读取和写入其他类型,
包括long,ulong,double和
十进制,以及用户定义的
类型,不能保证是
原子。
Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.
确定,所以阅读一个 double
is not atomic。这意味着这个值可能会被中间读取,对吧?那么,如何以原子方式读取 double
value?
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?
我注意有一个 Interlocked.Read
方法为 long
值。这对我来说是有道理的,因为读取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
for double
values,即使 System.Double
是一个64位值。
But there's no Interlocked.Read
for double
values, even though System.Double
is a 64-bit value.
我的程序中看到一些奇怪的行为,我的GUI显示一个 double
,而 double
也被其他线程频繁更新,显示正确的值(在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.
也许这是一个线程问题,或者也许是别的东西。但首先我想缩小可能性。所以:正在阅读一个 double
线程安全?
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屋!