Re: double-checked locking for singleton pattern
On 16 ???, 00:04, Marcin Swiderski <sfider.b...@gmail.com> wrote:
On 14 Maj, 23:12, kse...@yandex.ru wrote:> Singleton::Singleton()
{
... // do necessary initialisation
pInstance = this;
}
You do nothing to prevent compiler from changing the above code into:
Singleton::Singleton()
{
pInstance = this;
... // do necessary initialisation}
Thank you for the comment. I have realized that by reading the article
more attentively.
But what I still don't understand in it is the text on the page 11.
The authors claim that
the following code ensures proper initialisation order (the code is
already optimized):
Singleton* Singleton::instance()
{
if (pInstance == 0) {
Lock lock;
if (pInstance == 0) {
Singleton* volatile temp =
static_cast<Singleton*>(operator new(sizeof(Singleton)));
static_cast<volatile int&>(temp->x) = 5;
pInstance = temp;
}
}
}
but then they are saying that "Unfortunately, this all does nothing
to address the first problem: C++'s abstract machine is single-
threaded,
and C++ compilers may choose to generate thread-unsafe code from
source
like the above, anyway."
I wonder how this may happen, i.e. what multi-threaded compiler might
be doing wrong about that code?
Cheers,
Sergei
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]