Consider this:
class A {
public:
A(const char* s) { /*...*/ };
static const A& get_default() { /* avoid static data memember init fiasco */
static const A& a = A("default"); /* ..but not thread-safe */
return a;
}
};
How can I make get_default() thread safe? Or how can I find a way to get the A::a avoiding both the data member init fiasco and concurrency. I prefer not to use any locks.
The following will take advantage of the fact that initialization before
main()is called will take place on a single thread, and that thepInstancepointer must be zero initialized before dynamic initialization of static objects takes place (3.6.2 “Initialization of non-local objects”).So,
pInstancewill be NULL the first time thatget_default()is called – whether or not that call is due to the initialization ofA::pInstance. That will causeget_default()to initialize it (pInstancewill get ‘needlessly’ overwritten with the same value whenever it’s initializer runs – but that’ll be on the single init thread, so there are no threading issues). And just to be clear, the initializer forpInstancewill forceget_default()to be called on the init thread even if nothing else does.Subsequent calls to
get_default()will not modifypInstance, so it’s threadsafe.Note that the simpler:
Should also be threadsafe for the same reason, but it has a couple areas that make me a little less certain that it won’t have some potential drawbacks:
triggerisn’t used elsewhere (and this applies even if we take it out of the anonymous namespace), I’d worry that it might get removed from the program image. I’m not sure about what promises the standard might make about preventing this optimization – particularly ifclass Alives in a library.staticvariable inget_default()has been run before. However, there’s really no promise about what mechanism is used (I haven’t looked into what C++0x might say about this). With the first example, the threadsafe check after the init timeget_default()call is right there – guaranteed.