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.

相关文章