I have the following bit of C++11 code that uses threads and static variable initialisations. My question is:
What guarantees or assurances does the C++ language make about the single initialisation of static variables - the code below displays the correct values, however I can't seem to find the passage in the new standard that mentions how the memory model should interact with threads. When if ever do the variables become thread-local?
#include <iostream>
#include <thread>
class theclass
{
public:
theclass(const int& n)
:n_(n)
{ printf("aclass(const int& n){}\n"); }
int n() const { return n_; }
private:
int n_;
};
int operator+(const theclass& c, int n)
{
return c.n() + n;
}
void foo()
{
static theclass x = 1;
static theclass y = x + 1;
printf("%d %d\n",x.n(),y.n());
}
int main()
{
std::thread t1(&foo);
std::thread t2(&foo);
t1.join();
t2.join();
return 0;
}
The code will do what you expect. See §6.7.4
static local variables are:
... initialized the first time control passes over its declaration ... If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
In other words the compiler ensures your threads cooperate on the initialization of the static locals. They will each be initialized once and each thread will only have access to the object after it's been fully initialized.
The compiler will only create a thread local variable when explicitly requested with the thread_local
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With