Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

.net - C# volatile double

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; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...