我一直在 SO 和 MSDN 上四处寻找这个问题的答案,但似乎找不到明确的最终答案......
I've been looking all around SO and MSDN for an answer to this question, but cannot seem to find a clear and final answer...
我知道它在 C++11 标准中并且当前的 GCC 版本是这样的,但是 VC2010 当前是否保证局部静态变量初始化的线程安全?
I know that it's in the C++11 standard and that current GCC version behave this way, but does VC2010 currently guarantees thread-safety of a local static variable initialization?
即:VC2010 线程安全吗?
i.e.: Is this thread-safe with VC2010?
static S& getInstance()
{
static S instance;
return instance;
}
...如果没有,使用 VC2010 在 C++ 中获得线程安全的单例实现的当前最佳实践是什么?
...And if not, what is the current best practice to get a thread-safe singleton implementation in C++ with VC2010?
正如 Chris Betti 的回答所指出的,VC2010 没有实现局部静态变量 init 的线程安全性.
来自 Visual Studio 2010 的 静态文档:
From Visual Studio 2010's documentation on Static:
在多线程应用程序中为静态局部变量赋值不是线程安全的,我们不建议将其作为编程实践.
Assigning a value to a static local variable in a multithreaded application is not thread safe and we do not recommend it as a programming practice.
您问题的第二部分有一些很好的现有答案.
2015 年 11 月 22 日更新:
Updated Nov 22, 2015:
其他人已经证实,特别是静态初始化也不是线程安全的(请参阅评论和其他答案).
Others have verified, specifically, that static initialization is not thread safe either (see comment and other answer).
VS2015 上的用户尖叫:
User squelart on VS2015:
您可能想补充一点,VS2015 终于做对了:https://msdn.microsoft.com/en-au/library/hh567368.aspx#concurrencytable(魔术静态")
you may want to add that VS2015 finally gets it right: https://msdn.microsoft.com/en-au/library/hh567368.aspx#concurrencytable ("Magic statics")
这篇关于VC2010 静态初始化线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!