[...]
well, i don't agree with that statement.
The statement is certainly correct for Posix, and I can't
imagine it not holding under Windows either. Most multithreaded
programs will never use volatile.
mutex, semaphore are methods to avoid race condition in
pre-emptive scheduling
Amongst other things. According to the Posix specification,
functions like pthread_mutex_lock and pthread_mutex_unlock must
also ensure memory synchronization (between threads *and*
between processes). If they didn't, multithreaded code couldn't
be made to work.
volatile is just to make sure compiler doesn't perform any
optimization on the code and makes sure that instructions are
assembled so that the value of the variable is read from the
actual memory every single time...
Maybe. The exact semantics of volatile are implementation
defined. And some of the more frequently used compilers (VC++,
g++, Sun CC) basically treat volatile as hardly more than a
comment, giving it essentially no useful additional semantics
what so ever (other than making the code slower).
If you're writing code for a multithreaded environment, you need
a compiler which supports multithreading. It's difficult: the
C++ standard, at least the last official version of the C++
standard, doesn't say anything about multi-threading, and most
of the threading standards (e.g. Posix) don't specify a C++
binding, so you're left to exterpolating the C binding to C++.
For some things, the exterpolation is obvious: an int in C++
should behave like an int in C, for example. For others,
however... under Solaris, Sun CC and g++ have very different
behavior in some circumstances (pthread_exit(), for example, or
construction of a local static variable). With regards to code
movement and volatile, however, the exterpolation is rather
straight forward. Posix gives volatile no meaning for
multithreading in C, so there's no reason to expect it to have
meaning in C++. And Posix forbids a Posix-conformant compiler
from moving memory accesses accross a certain number of critical
functions, such as pthread_mutex_lock---it seems reasonable to
expect a C++ compiler which claims Posix compliance to repect
this rule as well. (In practice, most compilers respect it
implicitely anyway, because they're not capable of optimizing
through a function for which they have no sources.)