C++ 11函数局部静态const对象的线程安全初始化

gal*_*tte 4 c++ static multithreading initialization c++11

这个问题已在C++ 98上下文中提出,并在该上下文中得到了回答,但没有明确说明C++ 11

const some_type& create_const_thingy()
{
    lock my_lock(some_mutex);
    static const some_type the_const_thingy;
    return the_const_thingy;
}

void use_const_thingy()
{
    static const some_type& the_const_thingy = create_const_thingy();

    // use the_const_thingy
}
Run Code Online (Sandbox Code Playgroud)

这种初始化模式是否可以确保:

  1. 没有竞争条件发生
  2. create_const_thingy 只被召唤一次
  3. 如果我们删除互斥锁,这仍然有效吗?

提前致谢!

krz*_*zaq 8

从C++ 11开始,所有静态局部变量都保证以线程安全的方式初始化一次.

根据cppreference:

如果多个线程同时尝试初始化相同的静态局部变量,则初始化只发生一次(对于任意函数,可以获得类似的行为std::call_once).注意:此功能的常规实现使用双重检查锁定模式的变体,这可以将已初始化的局部静态的运行时开销减少到单个非原子布尔比较.

所以,对于你的问题: