E.g., can the following code ever print "3" for one of the threads?
int foo() { static int a = 1; return ++a; } void thread1() { cout<<foo()<<endl; } void thread2() { cout<<foo()<<endl; } edit: It's C++ 98
Of course it can print 3. It is even the "usual semantics" of this code to do so. Thread 1 initializes it with 1 and increments it, so it is 2. Thread 2 increments it again, so it is 3.
So, yes, scoped static variables are static, i.e., global variables. They are shared by threads.
Of course, the code has a race condition, so the result can possibly be anything, but 3 is a possible result.
++a), so there are no "usual semantics".[intro.multithread]/21: The execution of a program contains a data race if it contains two conflicting actions in dierent threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.local static variables are shared between threads.
Initialisation of function-local static variables is thread-safe in C++11 (before that, threads did not even exist ;)).
Modification of function-local static variables, on the other hand, is not thread-safe, so your modified code has undefined behaviour (due to the race condition).
2. And there is no race-condition, because the initialization ofais automatically synchronized.