TravisG
TravisG

Reputation: 2373

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

Upvotes: 4

Views: 7076

Answers (2)

Mankarse
Mankarse

Reputation: 40633

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

Upvotes: 3

gexicide
gexicide

Reputation: 40098

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.

Upvotes: 8

Related Questions