Re: Singleton initialization DCLP
On 2011-04-27 18:03:22 -0400, Joshua Maurice said:
On Apr 27, 11:35?am, "MikeWhy" <boat042-nos...@yahoo.com> wrote:
In context of the recent discussion of lazy initialization of singletons and
DCLP, is the behavior of the following safe, undefined, or unsafe?
class Foo {
...
protected:
? Foo();
public:
? static Foo & Instance()
? {
? ? ?static Foo singleton;
? ? ?return singleton;
? }
};
For C++03 with POSIX pthreads and win32 threads implementations, this
lazy initialization is "not thread safe". Specifically, if the first
call to Instance() is not happens-before all other calls, aka if the
first calls are concurrent, then you have an effective race condition,
aka undefined behavior.
Just a little thing on terminlology: "happens before" (without the
hyphen, but that's minor) is the correct technical term, but it can
also be used (and is so used in the C++0x draft) in the form "happen
before". It's less stilted to say "if any other call happens before the
first call to Instance()" or "if the first call to Instance() does not
happen before all other calls...". You might want to put "happen
before" in quotes to call out that it's a technical term. (In the
draft, happens before in its various forms is (supposed to be) always
followed by a cross-reference to its definition) Most of the threading
terms were chosen with this sort of usage in mind.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)