Some Questions about Volatile

E

Eric

I have some questions about the volatile keyword...

1) If I use the volatile keyword with a reference type such as a class like
so:

public volatile UserTotals totals = new UserTotals();

Are the fields of the class also protected? Or is it just the 4-8 byte
reference to the object that is protected?

2) Why doesn't volatile support 64bit and 128bit data types such as ulong or
decimal?

3) In the MSDN documentation, it says that all static members are
thread-safe. So why do code examples in the MSDN documentation use the
volatile keyword with static members?

Thanks
 
J

Jon Skeet [C# MVP]

Eric said:
I have some questions about the volatile keyword...

1) If I use the volatile keyword with a reference type such as a class like
so:

public volatile UserTotals totals = new UserTotals();

Are the fields of the class also protected? Or is it just the 4-8 byte
reference to the object that is protected?

It's only the reference, although volatile reads and writes involve
memory barriers which do have an effect on thread-safety in general.
Of course, if you do:

UserTotals foo = totals;
foo.x = 1;
foo.y = 2;

etc

then only one volatile read is involved.
2) Why doesn't volatile support 64bit and 128bit data types such as ulong or
decimal?

Presumably because this makes the CLR implementation significantly
harder or less efficient.
3) In the MSDN documentation, it says that all static members are
thread-safe. So why do code examples in the MSDN documentation use the
volatile keyword with static members?

Static members aren't *inherently* thread-safe - the MSDN docs are
saying that the class they're talking about has been designed to *be*
thread-safe. Using volatile variables is one of the tools you can use
to achieve thread safety.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top