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.
iwill not be static in memory, because it is not static. If, on the other hand, you had written:Then it would not be thread safe (well, if
iwas 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.