Re: When is "volatile" used instead of "lock" ?

Tech-Archive recommends: Speed Up your PC by fixing your registry



"Barry Kelly" <barry.j.kelly@xxxxxxxxx> wrote in message news:bea953lm6mqnu24mrik16j89b1oprglgpo@xxxxxxxxxx
Willy Denoyette [MVP] wrote:

I also don't agree with your statement that you should *always* use volatile
in lock free or low lock scenario's.

As far as I can see from the rest of your post, I think you've made a
mis-statement here. I think what you mean to say is that you shouldn't
use lock-free or low-locking unless there's no alternative, not that
volatile shouldn't be used - because volatile is usually very necessary
in order to get memory barriers right in those circumstances.

IMO, you should almost never use
volatile, unless you perfectly understand the semantics of the memory model
of the CLR/CLI (ECMA differs from V1.X differs from V2 for instance) and the
memory model of the CPU (IA32 vs. IA64). The last year I was involved in the
resolution of a number of nasty bugs , all of them where the result of
people trying to out-smart the system by applying lock free or low lock
techniques using volatile, since then whenever I see volatile I'm getting
very suspicious, really.......

I agree with you about seeing 'volatile' and it raising red flags, but
the cure is to use proper locking if possible, and careful reasoning
(rather than shotgun 'volatile' and guesswork), rather than simply
omitting 'volatile'.


Well, I wasn't suggesting to omit 'volatile, sorry hif I gave this impression. What I meant was, that you should be very if when looking for lock-free or low locking alternatives, and if you do, that you should not "always" use volatile.
Note that there are alternatives to volatile fields, there are Thread.MemoryBarrier, Thread.VolatileRead, Thread.VolatileWrite and the Interlocked API's, and these alternatives have IMO the (slight) advantages that they "forces" developers to reason about their usage, something which is less the case (from what I've learned when talking with other devs. across several teams) with volatile.
But here also, you need to be very careful, (the red flag should be raised whenever you see any of these too). You need to reason about their usage and that's the major problem when writing threaded code, even experienced developer have a hard time when reasoning about multithreading using locks, programming models that require to reason about how and when to use explicit fences or barriers are IMO too difficult, even for experts, to use reliably in mainstream computing, and this is what .NET is all about isn't it?.

Willy.


Willy.

.


Quantcast