[英]Is the dynamic initialization of the non-local variable thread-safe
I have following code in one of the source file of my application:我的应用程序的源文件之一中有以下代码:
// file1.cpp
#include <memory>
static auto global_variable = std::make_unique<int>(123);
int get_global_variable() { return *global_variable; }
Let assume that my application has some threads which call the get_global_variable
.假设我的应用程序有一些调用
get_global_variable
的线程。 Is the initialization of the global_variable
thread-safe? global_variable
的初始化是线程安全的吗?
As far as I know, the global_variable
is dynamically initialized .据我所知,
global_variable
是动态初始化的。 I also know that the initialization of static local variables is thread-safe since C++11.我也知道 static 局部变量的初始化是线程安全的,因为 C++11。 So, I wonder to know if that exception proves the rule that the other types of variables are not thread-safe initialized or it is also thread-safe and does not produce data races .
所以,我想知道这个异常是否证明了其他类型的变量不是线程安全初始化的规则,或者它也是线程安全的并且不会产生数据竞争。
I've found this answer , but after reading, I'm more confused because the answerer suggested using such pattern:我找到了这个答案,但是阅读后,我更加困惑,因为回答者建议使用这种模式:
const T& f()
{
static T t(a,b,c);
return t;
}
which supposedly guarantees the thread-safe initialization.据说可以保证线程安全的初始化。
I also found this answer .我也找到了这个答案。 It states that all globals are initialized before main, so there is only one thread ( Peter rightly pointed out that it is not true - or not every time).
它指出所有全局变量都在 main 之前初始化,因此只有一个线程(彼得正确地指出这不是真的 - 或者不是每次都如此)。 However, what if my piece of code is a shared library loaded by
dlopen
function to a program where there is more than one thread?但是,如果我的一段代码是由
dlopen
function 加载到一个有多个线程的程序的共享库怎么办?
[basic.start.dynamic]/4 It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred.
[basic.start.dynamic]/4存储时长为static的非局部非内联变量的动态初始化是在main的第一条语句之前排序还是延迟,由实现定义。 If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized.
如果它被延迟,它强烈发生在任何非初始化之前 - 使用任何非内联 function 或在与要初始化的变量相同的翻译单元中定义的非内联变量。
I believe this requires the implementation to perform initialization of global variables in a thread-safe manner (if it chooses to defer such initialization).我相信这需要实现以线程安全的方式执行全局变量的初始化(如果它选择推迟这种初始化)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.