Re: Should I use mutex in this context?
On Tue, 28 Oct 2008 09:16:30 +0100, Ulrich Eckhardt
Doug Harrison [MVP] wrote:
If you're going to use InterlockedIncrement, I'd get rid of the volatile
and use InterlockedCompareExchange to perform the reads, e.g.
InterlockedCompareExchange(&flag, 0, 0).
Why? The implementation-defined semantics of volatile are doing the right
thing here (similar to the missing InterlockedRead() function) so why the
InterlockedCompareExchange is the missing InterlockedRead function.
I don't know the definedness of mixing InterlockedXXX with raw reads
(volatile or otherwise). For me, InterlockedXXX is a black box, and I don't
know the underlying mechanisms well enough to speculate. For all I know, it
does the expected thing. Then again, for all I know, it doesn't do the
expected thing. :)
It's only in VC2005 and later that volatile carries memory barrier
semantics and ordering WRT reads/writes of non-volatile objects. Even the
traditional definition of volatile kills performance, but the additional VC
baggage really pours it down the drain. I don't know how much "additional
overhead" using InterlockedCompareExchange imposes in comparison to a raw
VC2005 volatile read, but I expect if you can afford VC's volatile and
InterlockedXXX some of the time, you can do without volatile and use
InterlockedXXX all of the time.
The only thing I know for certain is that if I use the InterlockedXXX
functions across the board, there is no reason to use volatile, and it will
just plain work.
Finally, I'd like to reiterate what I mentioned in my original post, namely
that events are a lot better suited for handling the sort of thing we're
Visual C++ MVP