Note that there are some explanatory texts on larger screens.

plurals
  1. POThread safe lazy construction of a singleton in C++
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload