C++ C++;11函数本地静态常量对象的线程安全初始化
这个问题是在C++98上下文中提出的,并在该上下文中得到了回答,但关于C++11没有明确说明C++ C++;11函数本地静态常量对象的线程安全初始化,c++,multithreading,c++11,static,initialization,C++,Multithreading,C++11,Static,Initialization,这个问题是在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_typ
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
}
此初始化模式是否确保:
create\u const\u thingy
只调用一次提前谢谢 由于C++11,所有静态局部变量都保证以线程安全的方式只初始化一次 根据: 如果多个线程试图初始化同一个静态本地 同时,初始化只发生一次(类似 使用
std::call_once
)可以获得任意函数的行为。
注意:此功能的通常实现使用
双重检查锁定模式,可减少
已将局部静态初始化为单个非原子布尔值
比较
因此,对于您的问题: