开发者

How can I avoid static data member init fiasco in a thread-safe way?

Consider th开发者_如何学编程is:

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 the pInstance pointer must be zero initialized before dynamic initialization of static objects takes place (3.6.2 "Initialization of non-local objects").

class A {
public:
    A(const char* s) { /*...*/ };

    static const A& get_default() { 
        if (!pInstance) {
            static const A default_instance("default");
            pInstance = &default_instance;
        }
        return *pInstance;
    }

private:
    static A const* pInstance;
};

A const* A::pInstance = &A::get_default();

So, pInstance will be NULL the first time that get_default() is called - whether or not that call is due to the initialization of A::pInstance. That will cause get_default() to initialize it (pInstance will 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 for pInstance will force get_default() to be called on the init thread even if nothing else does.

Subsequent calls to get_default() will not modify pInstance, so it's threadsafe.

Note that the simpler:

class A {
public:
    A(const char* s) { /*...*/ };

    static const A& get_default() { 
        static const A& a = A("default"); /* ..but not thread-safe */
        return a;
    }
};

namespace {
    A const& trigger = A::get_default();
}

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:

  • if the toolchain determines that trigger isn'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 if class A lives in a library.
  • presumably the compiler simply checks a hidden static flag to determine if the initialization of the local static variable in get_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 time get_default() call is right there - guaranteed.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜