Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are scoped static variables shared between threads?

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

like image 888
TravisG Avatar asked Dec 21 '22 14:12

TravisG


2 Answers

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.

like image 102
gexicide Avatar answered Dec 23 '22 03:12

gexicide


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

like image 38
Mankarse Avatar answered Dec 23 '22 03:12

Mankarse