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