Re: double-checked locking for singleton pattern
as commented in many of the posts and the afore mentioned paper from
Andrei Alexandrescu & Scott Meyers, the problem is the lack of
barriers. But as they comment in the very same paper:
"
At this point, one might reasonably wonder why Lock isn?t also
declared volatile. After all, it?s critical that the lock be
initialized before we try to write to pInstance or temp. Well, Lock
comes from a threading library, so we can assume it either dictates
enough restrictions in its specification or embeds enough magic in its
implementation to work without needing volatile. This is the case with
all threading libraries that we know of.
"
So, what would be the problem with the following implementation:
Singleton *pInstance;
Singleton* Singleton::instance()
{
if (pInstance == 0) {
Lock lock_1;
if (pInstance == 0) {
static Singleton* volatile temp = new Singleton();
{
Lock lock_2;
pInstance = temp;
}
}
}
}
if lock_2 works as a barrier against optimization, pInstance will
never be assigned before the object is correctly constructed ...
cheers,
- jan
ps.: i'm pretty sure there must be a problem, it wouldn't be that
simple, but i can't see how :)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]