这个问题已在 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
}
此初始化模式能否确保:
- 没有发生竞争条件
-
create_const_thingy
只被调用一次
- 如果我们删除互斥锁,这仍然有效吗?
提前致谢!
自 C++11 起,所有静态局部变量都保证以线程安全的方式仅初始化一次。
As per 参考参数 http://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables:
如果多个线程尝试初始化同一个静态局部变量
变量同时发生,初始化只发生一次(类似
可以通过以下方式获得任意函数的行为std::call_once
)。
注意:此功能的通常实现使用以下变体
双重检查锁定模式,减少了运行时开销
已初始化的局部静态为单个非原子布尔值
比较。
那么,对于你的问题:
- yes
- yes
- yes
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)