Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static variable inialization and threads

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; 
}
like image 433
Xander Tulip Avatar asked Oct 17 '11 05:10

Xander Tulip


1 Answers

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.

like image 75
deft_code Avatar answered Sep 23 '22 23:09

deft_code