Re: MSDN volatile sample
George wrote:
:: Yes, I agree Bo!
::
::
:: We are a little off-topic now. :-)
::
:: I have made some self-study and analysis. I think volatile has
:: nothing to do with thread synchronization, i.e. if we want to
:: share some data between threads, we should use thread
:: synchronization approach, like mutex other than volatile --
:: volatile is not one of the thread synchronization approaches.
::
:: 1. mutex (and other synchronization approach) is used to control
:: thread synchronization;
::
:: 2. volatile is used to prevent compiler from optimization
::
:: (1) and (2) are totally two different things and should not be
:: mixed.
::
:: My confusion is, whether we should add both mutex and volatile to
:: the shared data? Because even if mutex could make thread shared
:: data in a safe synchronized way, we are not 100% sure whether at
:: compiler level, it will make some wrong optimization -- so using
:: volatile at the same time is safe?
Using both of them is unneccessary. Except when there is a special
compiler extension (like VC8, VC9) , volatile is not enough for thread
synchronization.
When you use something like a mutex, that also disables some
reordering of reads and writes, because either
- the compiler knows about mutexes, and behaves correctly, or
- the mutex is an OS level operation, so the compiler doesn't know
enough to optimize
Bo Persson