Re: double-checked locking for singleton pattern
On May 30, 6:35 am, pfei...@gmail.com wrote:
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 ...
Whether you use a lock or a barrier for synchronization, you need to
use the same object on all threads that need to be synchronized. In
particular lock_2 (assuming that it is actually locking a mutex, which
is not apparent from your code) is synchronizing with nobody: only one
thread will ever acquire it, so it is useless.
Also, AFAIK, nothing in your code, assuming a relaxed memory model,
guarantees that, if pinstance is != 0, it will actually point to a
valid object (and, no, I'm not talking about the fact you didn't zero
initialize it).
--
Giovanni P. Deretta
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]