非局部变量的动态初始化是否线程安全

Is the dynamic initialization of the non-local variable thread-safe

我的应用程序的一个源文件中有以下代码:

// file1.cpp
#include <memory>

static auto global_variable = std::make_unique<int>(123);

int get_global_variable() { return *global_variable; }

假设我的应用程序有一些调用 get_global_variable 的线程。 global_variable 的初始化是线程安全的吗?

据我所知,global_variabledynamically initialized. I also know that the initialization of static local variables is thread-safe since 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

我找到了这个answer,但是看完之后,我更加困惑了,因为回答者建议使用这样的模式:

const T& f()
{
    static T t(a,b,c);
    return t;
}

据说可以保证线程安全的初始化。

我也发现这个 answer. It states that all globals are initialized before main, so there is only one thread (Peter 正确地指出它不是真的 - 或者不是每次)。但是,如果我的一段代码是由 dlopen 函数加载到一个有多个线程的程序中的共享库怎么办?

[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. 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.

我认为这需要实现以线程安全的方式执行全局变量的初始化(如果它选择推迟这种初始化)。