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?
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.
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.
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.
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).
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.)
Unless explicitly declared as static, no they're not. They're on a stack, and each thread has a separate stack.
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