Re: Am I or Alexandrescu wrong about singletons?
On Tue, 23 Mar 2010 08:05:28 CST
"Leigh Johnston" <leigh@i42.co.uk> wrote:
[snip]
Sometimes you have to use common sense:
thread A:
finished = false;
spawn_thread_B();
while(!finished)
{
/* do work */
}
thread B:
/* do work */
finished = true;
If finished is not volatile and compiler optimizations are enabled
thread A may loop forever.
The behaviour of optimizing compilers in the real world can make
volatile necessary to get correct behaviour in multi-threaded
designs. You don't always have to use a memory barriers or a mutexes
when performing an atomic read of some state shared by more than one
thread.
It is never "necessary" to use the volatile keyword "in the real world"
to get correct behaviour because of "the behaviour of optimising
compilers". If it is, then the compiler does not conform to the
particular standard you are writing to. For example, all compilers
intended for POSIX platforms which support pthreads have a
configuration flag (usually "-pthread") which causes the locking
primitives to act also as compiler barriers, and the compiler would be
non-conforming if it did not both provide this facility and honour it.
Of course, there are circumstances when you can get away with the
volatile keyword, such as the rather contrived example you have given,
but in that case it is pretty well pointless because making the
variable volatile as opposed to using normal synchronisation objects
will not improve efficiency. In fact, it will hinder efficiency if
Thread A has run work before thread B, because thread A will depend on a
random future event on multi-processor systems, namely when the caches
happen to synchronise to achieve memory visibility, in order to proceed.
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]