C++ 静态成员变量初始化线程安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1962880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:43:02  来源:igfitidea点击:

Is C++ static member variable initialization thread-safe?

c++multithreadingstaticmember-variables

提问by Varuna

According to following resources, in C++(Specially Visual C++) scoped static variable initialization isn't thread safe. But, global static variables are safe.

根据以下资源,在 C++(特别是 Visual C++)范围内的静态变量初始化不是线程安全的。但是,全局静态变量是安全的。

Thread-safe static variables without mutexing?

没有互斥的线程安全静态变量?

http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx

http://blogs.msdn.com/oldnewthing/archive/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;

Thanks in advance!

提前致谢!

回答by Marcelo Cantos

It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.

这更多是函数范围的静态变量与其他所有类型的静态变量的问题,而不是范围与全局变量的问题。

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.

所有非函数作用域的静态变量都在 main() 之前构造,而只有一个活动线程。函数作用域静态变量在其包含的函数第一次被调用时被构造。当函数在多个线程上被调用时,该标准对如何构造函数级静态的问题保持沉默。但是,我使用过的每个实现都使用围绕构造函数的锁(带有两次检查的标志)来保证线程安全。

回答by Rom

Yes(*). When global statics are initialized, there is only one thread around and all constructors are called on it. This is not true for function's statics, though.

是的(*)。当全局静态被初始化时,周围只有一个线程并且所有的构造函数都在它上面被调用。但是,对于函数的静力学而言,情况并非如此。

(*) One can possibly make global statics not thread-safe by creating threads in some of the constructors and scheduling some initialization stages on these threads. In this case usual thread safety rules apply.

(*) 通过在一些构造函数中创建线程并在这些线程上调度一些初始化阶段,可以使全局静态不是线程安全的。在这种情况下,通常的线程安全规则适用。