I know that that question may be seemed as a duplicate, but I haven't got the answer reading the other questions.
My situation - Visual C++ compiler 2005 from express edition studio + Windows sdk.
Just a question if a function like that:
void myFunc()
{
int i=0;
i++;
}
is safe to call from multiple threads?
Yes, it seems like it is, but won't the compiler make the i variable be static in the memory? So that could lead to that two threads are acting together on one memory region? Or my fears are just some fears of a fool? And all local variables are created in the moment of calling the function?
Yes, it is thread safe.
On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.
But: No, threads do not share real local variables. But in for example C#, a local variable may be captured or 'closed over' and then it becomes a different story.
Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.
Yes, it is thread safe.
i
will not be static in memory, because it is not static. If, on the other hand, you had written:
void myFunc()
{
static int i = 0;
i++;
}
Then it would not be thread safe (well, if i
was actually used).
Local variables are all located on the stack (or live entirely in registers). Each thread has its own stack, and registers are handled in such a way that they are essentially local to each thread (see Context Switching), so you are fine.
And all local variables are created in the moment of calling the function?
The typical implementation of local variables is to create them on the stack, and each thread has its own stack, so locals are fine.
The only time you have to watch out is when the variable is a complex type, because it may have logic within it that operates on static data or global data. Most good software will avoid writing classes like that, of course.
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