C++11 中的局部静态变量初始化线程安全吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8102125/
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
Is local static variable initialization thread-safe in C++11?
提问by Ralph Zhang
I know this is an often asked question, but as there are so many variants, I'd like to re-state it, and hopefully have an answer reflecting the current state. Something like
我知道这是一个经常被问到的问题,但由于有很多变体,我想重新陈述它,并希望有一个反映当前状态的答案。就像是
Logger& g_logger() {
static Logger lg;
return lg;
}
Is the constructor of variable lg guaranteed to run only once?
变量 lg 的构造函数是否保证只运行一次?
I know from previous answers that in C++03, this is not; in C++0x draft, this is enforced. But I'd like a clearer answer to
我从以前的答案中知道,在 C++03 中,这不是;在 C++0x 草案中,这是强制执行的。但我想要一个更明确的答案
- In C++11 standard (not draft), is the thread-safe initialization behavior finalized?
- If the above is yes, in current latest releases of popular compilers, namely gcc 4.7, vc 2011 and clang 3.0, are they properly implemented?
- 在 C++11 标准(非草案)中,线程安全的初始化行为是否最终确定?
- 如果以上是肯定的,那么在当前最新版本的流行编译器中,即 gcc 4.7、vc 2011 和 clang 3.0,它们是否正确实现?
采纳答案by Kerrek SB
The relevant section 6.7:
相关第 6.7 节:
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
这样一个变量在第一次控制通过它的声明时被初始化;此类变量在其初始化完成后被视为已初始化。[...] 如果在初始化变量时控件同时进入声明,则并发执行将等待初始化完成。
Then there's a footnote:
然后有一个脚注:
The implementation must not introduce any deadlock around execution of the initializer.
该实现不得在初始化程序的执行周围引入任何死锁。
So yes, you're safe.
所以是的,你很安全。
(This says nothing of course about the subsequent access to the variable through the reference.)
(这当然没有说明通过引用对变量的后续访问。)
回答by Denis Glotov
--fno-threadsafe-statics also worth mentioning. In gcc:
--fno-threadsafe-statics 也值得一提。在 gcc 中:
Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe.
不要发出额外的代码来使用 C++ ABI 中指定的例程进行局部静态的线程安全初始化。您可以使用此选项在不需要线程安全的代码中稍微减少代码大小。
Also, have a look at the old thread Are function static variables thread-safe in GCC?
另外,看看旧线程GCC中的函数静态变量是线程安全的吗?