Is C++ static member variable initialization thread-safe?(C++ 静态成员变量初始化线程安全吗?)
问题描述
根据以下资源,在 C++(特别是 Visual C++)范围内的静态变量初始化不是线程安全的.但是,全局静态变量是安全的.
According to following resources, in C++(Specially Visual C++) scoped static variable initialization isn't thread safe. But, global static variables are safe.
没有互斥的线程安全静态变量?
http://blogs.msdn.com/oldnewthing/存档/2004/03/08/85901.aspx
那么,以下带有静态成员变量的代码是线程安全的吗?
So, is following code with static member variable thread-safe?
class TestClass
{
public:
static MyClass m_instance;
}
Myclass TestClass::m_instance;
提前致谢!
推荐答案
更多是函数作用域静态变量与其他所有类型静态变量的问题,而不是作用域与全局变量的问题.
It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.
所有非函数作用域的静态变量都是在 main() 之前构造的,而只有一个活动线程.函数作用域的静态变量在它们的包含函数第一次被调用时被构造.当函数在多个线程上被调用时,该标准对如何构造函数级静态的问题保持沉默.但是,我使用过的每个实现都在构造函数周围使用了一个锁(带有两次检查的标志)以保证线程安全.
All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing function is called. The standard is silent on the question of how function-level statics are constructed when the function is called on multiple threads. However, every implementation I've worked with uses a lock around the constructor (with a twice-checked flag) to guarantee thread-safety.
这篇关于C++ 静态成员变量初始化线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 静态成员变量初始化线程安全吗?
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
