Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multithread safe local variables?

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?

like image 986
Evengard Avatar asked Jun 12 '11 22:06

Evengard


People also ask

Are local variables thread-safe in C?

Yes, it is thread safe.

Are local variables 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.

Are local variables shared between threads C#?

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.

Are local variables in static method thread-safe?

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.


2 Answers

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.

like image 165
Peter Alexander Avatar answered Sep 22 '22 05:09

Peter Alexander


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.

like image 37
Kylotan Avatar answered Sep 22 '22 05:09

Kylotan