Re: MSDN volatile sample
George wrote:
:: Thanks Alex,
::
::
:: I am wondering if you use mutex or other technologies, like
:: critical section or something, to synchronize/share the
:: cross-thread variable, do you think we still need the volatile
:: keyword?
No, not in this case.
The general use for volatile is in interfacing with external hardware.
A pointer to volatile char could be a port on video board, or
something. The volatile keyword tells the compiler that each read from
that address could give a different value, so it has to actually be
read each time, and not cached and reused.
::
:: I have this concern is because some other people in this discussion
:: mentioned that volatile is an alternative way to share data
:: between threads (alternatives are like mutex), so if other
:: approaches like critical section or mutex is used, volatile is no
:: need.
Right.
::
:: But I can not find any formal statements about this point from
:: MSDN.
MSDN describes Microsoft's implementation of C++, it is not a general
description. Specifically, you are reading the spec for VC++ 8.0,
which has an EXTENSION for volatile variables, making the guarantees
used in the example.
If you go back to older versions, like VC6 or VC7, it will not work
(or at least there are no guarantees). If you move the code to another
compiler, you will have to closely read its documentation, to see if
the guarantees still hold.
That's one good reason for not using volatile this way!
Bo Persson