<p>Is there a way to implement a singleton object in C++ that is:</p>

<ol>
<li>Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once).</li>
<li>Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables).</li>
</ol>

<p>(I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)?  If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..)</p>

<hr>

<p>Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being <strong>the answer</strong>).  There appears to be two broad solutions:</p>

<ol>
<li>Use static initialisation (as opposed to dynamic initialisation) of a POD static variable, and implementing my own mutex with that using the builtin atomic instructions.  This was the type of solution I was hinting at in my question, and I believe I knew already.</li>
<li>Use some other library function like <a href="http://opengroup.org/onlinepubs/007908799/xsh/pthread_once.html" rel="noreferrer">pthread_once</a> or <a href="http://www.boost.org/doc/libs/1_33_1/doc/html/call_once.html" rel="noreferrer">boost::call_once</a>.  These I certainly didn't know about - and am very grateful for the answers posted.</li>
</ol>

[{'answer_id': 6943, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 4, 'selected': False, 'text': '<p>Unfortunately, Matt\'s answer features what\'s called <em>double-checked locking</em> which isn\'t supported by the C/C++ memory model.  (It is supported by the Java 1.5 and later — and I think .NET — memory model.)  This means that between the time when the <code>pObj == NULL</code> check takes place and when the lock (mutex) is acquired, <code>pObj</code> may have already been assigned on another thread.  Thread switching happens whenever the OS wants it to, not between "lines" of a program (which have no meaning post-compilation in most languages).</p>\n\n<p>Furthermore, as Matt acknowledges, he uses an <code>int</code> as a lock rather than an OS primitive.  Don\'t do that.  Proper locks require the use of memory barrier instructions, potentially cache-line flushes, and so on; use your operating system\'s primitives for locking.  This is especially important because the primitives used can change between the individual CPU lines that your operating system runs on; what works on a CPU Foo might not work on CPU Foo2.  Most operating systems either natively support POSIX threads (pthreads) or offer them as a wrapper for the OS threading package, so it\'s often best to illustrate examples using them.</p>\n\n<p>If your operating system offers appropriate primitives, and if you absolutely need it for performance, instead of doing this type of locking/initialization you can use an <em>atomic compare and swap</em> operation to initialize a shared global variable.  Essentially, what you write will look like this:</p>\n\n<pre><code>MySingleton *MySingleton::GetSingleton() {\n    if (pObj == NULL) {\n        // create a temporary instance of the singleton\n        MySingleton *temp = new MySingleton();\n        if (OSAtomicCompareAndSwapPtrBarrier(NULL, temp, &amp;pObj) == false) {\n            // if the swap didn\'t take place, delete the temporary instance\n            delete temp;\n        }\n    }\n\n    return pObj;\n}\n</code></pre>\n\n<p>This only works if it\'s safe to create multiple instances of your singleton (one per thread that happens to invoke GetSingleton() simultaneously), and then throw extras away.  The <code>OSAtomicCompareAndSwapPtrBarrier</code> function provided on Mac OS X — most operating systems provide a similar primitive — checks whether <code>pObj</code> is <code>NULL</code> and only actually sets it to <code>temp</code> to it if it is.  This uses hardware support to really, literally only perform the swap <em>once</em> and tell whether it happened.</p>\n\n<p>Another facility to leverage if your OS offers it that\'s in between these two extremes is <code>pthread_once</code>.  This lets you set up a function that\'s run only once - basically by doing all of the locking/barrier/etc. trickery for you - no matter how many times it\'s invoked or on how many threads it\'s invoked.</p>\n'}, {'answer_id': 6955, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 5, 'selected': True, 'text': "<p>Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables).  In general, no, this is not possible.  You need something available for synchronization.</p>\n\n<p>As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is executed.  This makes it possible to use a statically-initialized mutex to synchronize creation of the singleton.</p>\n\n<p>From the 2003 revision of the C++ standard:</p>\n\n<blockquote>\n  <p>Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.</p>\n</blockquote>\n\n<p>If you <em>know</em> that you will be using this singleton during the initialization of other static objects, I think you'll find that synchronization is a non-issue.  To the best of my knowledge, all major compilers initialize static objects in a single thread, so thread-safety during static initialization.  You can declare your singleton pointer to be NULL, and then check to see if it's been initialized before you use it.</p>\n\n<p>However, this assumes that you <em>know</em> that you'll use this singleton during static initialization.  This is also not guaranteed by the standard, so if you want to be completely safe, use a statically-initialized mutex.</p>\n\n<p>Edit: Chris's suggestion to use an atomic compare-and-swap would certainly work.  If portability is not an issue (and creating additional temporary singletons is not a problem), then it is a slightly lower overhead solution.</p>\n"}, {'answer_id': 7036, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 3, 'selected': False, 'text': '<p>You can\'t do it without any static variables, however if you are willing to tolerate one, you can use <a href="http://www.boost.org/doc/html/thread.html" rel="noreferrer">Boost.Thread</a> for this purpose. Read the "one-time initialisation" section for more info.</p>\n\n<p>Then in your singleton accessor function, use <code>boost::call_once</code> to construct the object, and return it.</p>\n'}, {'answer_id': 7044, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 1, 'selected': False, 'text': '<p>While this question has already been answered, I think there are some other points to mention:</p>\n\n<ul>\n<li>If you want lazy-instantiation of the singleton while using a pointer to a dynamically allocated instance, you\'ll have to make sure you clean it up at the right point.</li>\n<li>You could use Matt\'s solution, but you\'d need to use a proper mutex/critical section for locking, and by checking "pObj == NULL" both before and after the lock. Of course, <strong>pObj</strong> would also have to be <em>static</em> ;)\n.\nA mutex would be unnecessarily heavy in this case, you\'d be better going with a critical section.</li>\n</ul>\n\n<p>But as already stated, you can\'t guarantee threadsafe lazy-initialisation without using at least one synchronisation primitive.</p>\n\n<p>Edit: Yup Derek, you\'re right. My bad. :)</p>\n'}, {'answer_id': 7052, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>You could use Matt\'s solution, but you\'d need to use a proper mutex/critical section for locking, and by checking "pObj == NULL" both before and after the lock. Of course, pObj would also have to be static ;) . A mutex would be unnecessarily heavy in this case, you\'d be better going with a critical section.</p>\n</blockquote>\n\n<p>OJ, that doesn\'t work.  As Chris pointed out, that\'s double-check locking, which is not guaranteed to work in the current C++ standard.  See: <a href="http://www.ddj.com/184405726" rel="nofollow noreferrer">C++ and the Perils of Double-Checked Locking</a></p>\n\n<p>Edit: No problem, OJ.  It\'s really nice in languages where it does work.  I expect it will work in C++0x (though I\'m not certain), because it\'s such a convenient idiom.</p>\n'}, {'answer_id': 18293, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 0, 'selected': False, 'text': "<p>I suppose saying don't do this because it's not safe and will probably break more often than just initializing this stuff in <code>main()</code> isn't going to be that popular.</p>\n\n<p>(And yes, I know that suggesting that means you shouldn't attempt to do interesting stuff in constructors of global objects. That's the point.)</p>\n"}, {'answer_id': 70994, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 3, 'selected': False, 'text': "<p>For gcc, this is rather easy:</p>\n\n<pre><code>LazyType* GetMyLazyGlobal() {\n    static const LazyType* instance = new LazyType();\n    return instance;\n}\n</code></pre>\n\n<p>GCC will make sure that the initialization is atomic. <strong>For VC++, this is not the case</strong>. :-(</p>\n\n<p>One major issue with this mechanism is the lack of testability: if you need to reset the LazyType to a new one between tests, or want to change the LazyType* to a MockLazyType*, you won't be able to. Given this, it's usually best to use a static mutex + static pointer.</p>\n\n<p>Also, possibly an aside: It's best to always avoid static non-POD types. (Pointers to PODs are OK.) The reasons for this are many: as you mention, initialization order isn't defined -- neither is the order in which destructors are called though. Because of this, programs will end up crashing when they try to exit; often not a big deal, but sometimes a showstopper when the profiler you are trying to use requires a clean exit.</p>\n"}, {'answer_id': 1702537, 'author': 'n-alexander', 'author_id': 23420, 'author_profile': 'https://Stackoverflow.com/users/23420', 'pm_score': 1, 'selected': False, 'text': '<ol>\n<li><p>read on weak memory model. It can break double-checked locks and spinlocks. Intel is strong memory model (yet), so on Intel it\'s easier</p></li>\n<li><p>carefully use "volatile" to avoid caching of parts the object in registers, otherwise you\'ll have initialized the object pointer, but not the object itself, and the other thread will crash</p></li>\n<li><p>the order of static variables initialization versus shared code loading is sometimes not trivial. I\'ve seen cases when the code to destruct an object was already unloaded, so the program crashed on exit</p></li>\n<li><p>such objects are hard to destroy properly</p></li>\n</ol>\n\n<p>In general singletons are hard to do right and hard to debug. It\'s better to avoid them altogether.</p>\n'}, {'answer_id': 2867416, 'author': 'Frerich Raabe', 'author_id': 91757, 'author_profile': 'https://Stackoverflow.com/users/91757', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s a very simple lazily constructed singleton getter:</p>\n\n<pre><code>Singleton *Singleton::self() {\n    static Singleton instance;\n    return &amp;instance;\n}\n</code></pre>\n\n<p>This is lazy, and the next C++ standard (C++0x) requires it to be thread safe. In fact, I believe that at least g++ implements this in a thread safe manner. So if that\'s your target compiler <em>or</em> if you use a compiler which also implements this in a thread safe manner (maybe newer Visual Studio compilers do? I don\'t know), then this might be all you need.</p>\n\n<p>Also see <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2513.html" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2513.html</a> on this topic.</p>\n'}]
['https://Stackoverflow.com/questions/6915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755/']