是C ++的静态成员变量初始化线程安全吗? [英] Is C++ static member variable initialization thread-safe?

查看:587
本文介绍了是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.

这篇关于是C ++的静态成员变量初始化线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆