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

是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://stackoverflow.com/questions/1052168/thread-safe-static-variables-without-mutexing

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;

提前感谢!

这是一个问题,功能范围的静态变量与其他种类的静态变量,而不是范围与全局。

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.