开发者

Should volatile be used with a (non-concurrent) collection?

开发者 https://www.devze.com 2023-03-16 00:35 出处:网络
I\'m familiar with the basic idea of volatile (to prevent compiler optimization of instructions involving values that may be accessed from multiple threads, in summary), but I\'ve noticed that example

I'm familiar with the basic idea of volatile (to prevent compiler optimization of instructions involving values that may be accessed from multiple threads, in summary), but I've noticed that examples I've found involving volatile and .NET 3.5 collections (NOT .NET 4 Concurrent collections. I know what they are but my current context does not allow me to use .NET 4.) never have volatile applied to the collection its开发者_Python百科elf. Of course the collection (or a corresponding locking object) will need to be locked when accessing it from multiple threads, but is there a reason that a collection should not be marked volatile? Is the type of collection significant (i.e. a List of value types versus a List of reference types)?


Volatile almost certainly doesn't mean what you think it does. That's the main reason for not using it. (These days I refuse to try to describe what volatile means. It's too complicated to explain neatly, and it's almost always the wrong approach unless you're a memory model expert, in which case you definitely don't need me to explain it to you.)

If you're locking on an appropriate object, what benefit do you believe it will give you? You're already going to be going through appropriate memory fences in acquiring and releasing the lock... I suspect any reasons for using volatile for the variable itself are based on a misunderstanding.


Unless you are actually changing the reference for the collection (i.e., repeatedly assigning a new collection to a variable referring to a collection) there is no reason to mark that variable as volatile (that is, it is not doing what you think it does).

Even if you are (and then I will question what you are doing???), it's not clear that you would need volatile if you are locking properly.

By the way, this subject is really hard. really, Really, REALLY hard.


If you aren't changing the reference (i.e. creating an entire new unrelated collection and replacing that in the field), then volatile will do nothing. Personally, I'd probably make the collection field readonly in thread-intensive cases just to prevent accidents (and use lock).

So probably: no.


You just need to use a lock. There's no call for volatile in what you describe.


If you mark collection by volatile you just mark reference itself, not a whole collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消