Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local variables of static member functions

Tags:

c++

Today we came accross a problem concerning static member functions in an multithreaded environment. The question we asked ourselves and couldn't find a satisfying answer is: are local varialbes of static member functions static as well?

// header

class A
{
  static int test();
}

// implementation
int A::test()
{
  int a = rand();
  int b = rand();
  int c = a + b;

  return c;
}

Say you have two threads both calling A::test(). Is it possible that while thread 1 proccesses c = a + b thread 2 enters test() and changes the value of a by assigning the new return value of rand() or in other words do both threads operate an the some memory locations for a, b and c?

like image 938
codencandy Avatar asked Mar 03 '10 15:03

codencandy


People also ask

What are static local variables?

A local static variable is a variable, whose lifetime doesn't stop with a function call where it is declared. It extends until the lifetime of a complete program. All function calls share the same copy of local static variables. These variables are used to count the number of times a function is called.

Can a static method use local variables?

In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.

What are static member variables and functions?

Static Member Variablessuppose in a function there are 2 variables, one is a normal variable and the other one is a static variable. The normal variable is created when the function is called and its scope is limited. While the static variable is created once and destroyed at the end of the program.

Where is local static variables stored?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).


2 Answers

No. The stack frames are independent for each thread's invocation of the function, and each gets its own locals. (You do need to be careful if you're accessing actual shared data e.g. static members in the class.)

like image 109
Ben Zotto Avatar answered Sep 24 '22 12:09

Ben Zotto


Unless explicitly declared as static, no they're not. They're on a stack, and each thread has a separate stack.

like image 37
Seva Alekseyev Avatar answered Sep 25 '22 12:09

Seva Alekseyev