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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.