Re: Question on using volatile in a return type
On Dec 29, 12:59 am, Ichthyostega <Ichthyost...@web.de> wrote:
actually I am asking as well about semantics and best practices...
To start with, I am waiting on a condition variable (in a loop
that is). The actual condition is a bool flag located
elsewhere, which is to be passed in as a function parameter.
So the correct type would be "volatile bool&"
void func1 (volatile bool& flag) {
// init...
while (!flag && !err)
err = pthread_cond_wait (&cond, &mutex);
// ...
}
The "volatile" should give the compiler a hint not to employ
optimisations but fetch the value from the original location,
where it may have been changed by another thread meanwhile --
is this correct?
Formally, the meaning of "volatile" is largely implementation
dependent; the standard waffles a bit about "access", but
doesn't say what it means by an access (and the C standard says
explicitly: "What constitutes an access to an object that has
volatile-qualified type is implementation-defined.") In
practice, the compilers I know (Sun CC, g++ and VC++) don't
define it to be anything useful.
If you're waiting on a conditional variable, of course, you
don't need volatile, because all necessary synchronization has
been provided by the system requests (e.g. pthread_cond_wait,
pthread_cond_signal and pthread_cond_broadcast under Posix).
And: does the flag referred to have to be declared as volatile
at the original location? (usually somewhere in a class?). Or
is it sufficient to define the reference as volatile bool& ?
Volatile generally isn't relevant to threading. You don't need
it anywhere. (At least for the systems I'm familiar with: Posix
and Windows. A system certainly could define its threading
primitives in a way that made volatile relevant, and require
that compilers implement it in a corresponding way.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34