Re: Is this safe?
Dragan Milenkovic wrote:
Andre Kaufmann wrote:
Joshua Maurice wrote:
[...]
In order for the changes to be "visible" to all cores, there has to
be a matching memory barrier instruction _before_ reading a variable.
There is none before the first "if (!instance_)", so at that point
the core can "see" a non-null instance_, but can "see" *instance_
You mean if one thread is at the line
instance_ = &theInstance;
and another one is testing instance_ and returns this value, just before
the memory barrier has been executed ?
[Object initialization and pointer assignment are write operations,
which won't be reordered on x86/x64 - for heavens sake I referred to
that platforms only to be sure that the code is safe ;-) ]
Isn't that just a theoretical problem, because the access to the
returned object itself must be synchronized (by memory barriers) either,
because it will be accessed by multiple threads ?
from the time before the constructor did its job. This is why
double-checked locking fails.
But I agree - may be (potentially) a point (for other CPU platforms):
Besides adding proprietary instructions for dedicated platforms like
[sfence], shouldn't the more resource intensive change:
AccessLock<CriticalSection> access(key_1);
if ( !instance_ )
{
AccessLock<CriticalSection> access2(key_2);
static Singleton<T> theInstance;
access2.LeaveCriticalSection();
instance_ = &theInstance;
}
do the trick, for situations where theory doesn't match practice ?
And shouldn't this make the code safe for all common CPU platforms,
where CriticalSection does use memory barriers ?
Andre
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]