mardi 26 janvier 2021

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. Is the initialization of the global_variable thread-safe?

As far as I know, the global_variable is dynamically 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.

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

Aucun commentaire:

Enregistrer un commentaire