C#挥发性双 [英] C# volatile double

查看:149
本文介绍了C#挥发性双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于只有引用类型和一些原语(包括浮动,但不会增加一倍,我不知道为什么,我很高兴地听到,为什么的原因)可以被声明为挥发,如果我换了双一类那么声明为挥发性(如下图),将双重属性进行读写线程安全的,因为任何其他挥发性,或者我应该还是在看锁?

 公共类MyThreadedClass
{
    挥发性VolatileDouble voldub;
}

公共类VolatileDouble
{
    公共双人大床{获得;组; }
}
 

解决方案

之所以双重不能声明挥发性:这是64位的,这使得它比基于x86字的大小,而起价地为p $ pvents它声明为volatile的CLI,如果我没记错的话。

以您目前的答案,只有引用的被视为是挥发性的。这意味着内存模型将确保它总是使用最新的参考,但它仍然使用过时的值。

我会用锁,如果我是你去,但有另一种方法是使用<一个href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.read.aspx"><$c$c>Interlocked.Read Interlocked.Exchange 作用于多头在与<连词href="http://msdn.microsoft.com/en-us/library/system.bitconverter.int64bitstodouble.aspx"><$c$c>BitConverter.Int64BitsToDouble和<一href="http://msdn.microsoft.com/en-us/library/system.bitconverter.doubletoint64bits.aspx"><$c$c>BitConverter.DoubleToInt64Bits.你可以在 VolatileDouble 结构内封装这一点。 (我可能会使其成为一个结构,而不是一类。)

As only reference types and a few primitives (including float, but not double, I'm not sure the reason why, I'm happy to hear why) can be declared as volatile, if I wrap a double in a class then declare it as volatile (as below), will the double property be 'read write' thread safe as any other volatile, or should I still be looking at locking?

public class MyThreadedClass
{
    volatile VolatileDouble voldub;
}

public class VolatileDouble
{
    public double Double { get; set; }
}

解决方案

Reason why double can't be declared volatile: it's 64 bits, which makes it more than the word size on x86, which prevents it from being declared volatile in the CLI if I remember correctly.

With your current answer, only the reference is treated as being volatile. That means the memory model will make sure it always uses the most recent reference, but it could still use a stale value.

I'd go with locking if I were you, but one alternative is to use Interlocked.Read and Interlocked.Exchange acting on longs, in conjunction with BitConverter.Int64BitsToDouble and BitConverter.DoubleToInt64Bits. You could encapsulate this within a VolatileDouble struct. (I'd probably make it a struct rather than a class.)

这篇关于C#挥发性双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆