开发者

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 cr开发者_如何学编程eated in the moment of calling the function?


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.


The compiler cannot make your variables static, as that changes the semantics of the program. As long as you stick to variables declared only on your stack, then you can guarantee thread-safety.


@PeterAlexander has probably answered the case you're worried about, but another case where it would not be safe is if i was a global variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜