modern c++(2)-局部静态变量线程安全

2019-07-17  本文已影响0人  RC_HT

局部静态变量

局部静态变量就是定义在函数内部的静态变量。它的初始化发生在该函数第一次被调用执行到局部静态变量定义语句时
利用这一点可以用来实现懒汉式(lazy)单例模式

static Singleton &getInstance() {
    static Singleton instance;
    return instance;
}

但在C++98/03标准中,这一代码并不是线程安全的,因为上述代码相当于编译器帮你生成了是否初始化的过程,只是没有考虑线程安全性。

static Singleton& instance()
{
    static bool initialized = false;
    static char buf[sizeof(Singleton)];

    if (!initialized) {
        initialized = true;
        new(&buf) Singleton();
    }

    return (*(reinterpret_cast<Singleton*>( &buf)));
}

线程安全

C++11改进了这一情况,保证了线程安全:

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

上一篇 下一篇

猜你喜欢

热点阅读