C ++ local variables and threads (not thread_local)

What are the C ++ 98 and C ++ 11 memory models for local arrays and interaction with threads?

I am not referring to the C ++ 11 thread_local keyword , which refers to global and static variables.

Instead, I would like to know what guaranteed flow behavior is for arrays that are allocated at compile time. By compilation time, I mean "int array [100]", which differs from distribution using the new keyword []. I do not mean static variables.

For example, let's say I have the following struct / class:

struct xyz { int array[100]; }; 

and the following function:

 void fn(int x) { xyz dog; for(int i=0; i<100; ++i) { dog.array[i] = x; } // do something else with dog.array, eg. call another function with dog as parameter } 

Is it safe to call fn () from multiple threads? It seems like a C ++ memory model: all local non-static variables and arrays are distributed on the stack, and each thread has its own stack. Is this true (i.e. is this an official part of the standard)?

+6
source share
2 answers

Such variables are allocated on the stack, and since each thread has its own stack, it is completely safe to use local arrays. They do not differ from, for example, local int s.

+8
source

C ++ 98 did not say anything about threads. Programs written in C ++ 98, but which use streams, do not have the value defined by C ++ 98. Of course, for stream extensions it is advisable to provide stable private local variables for streams, and they usually do this. But there may be threads for which this is not the case: for example, processes created by vfork on some Unix systems, as a result of which the parent and child will run on the same stack stack, since v in vfork means that there is no cloning of the address space, and vfork does not redirect the new process to another function.

C ++ 11 supports thread support. Local variables in separate activation chains in separate C ++ 11 threads do not interfere. But if you go beyond the limits of the language and throw out vfork or something similar to it, then all bets are disabled, as before.

But here is something. C ++ now has a closure. What if two threads simultaneously cause the same closure? Then you have two threads that use the same local variables. Closing is like an object, and its captured local variables are members. If two or more threads call the same closure, then you have a de facto multi-threaded object whose members (i.e., captured lexical variables) are shared.

A stream can also simply pass the address of its local variables to another stream, thereby causing them to be shared.

+2
source

All Articles