Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ local variables and threads (not thread_local)

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

I'm not referring to the C++11 thread_local keyword, which pertains to global and static variables.

Instead, I'd like to find out what is the guaranteed behavior of threads for arrays that are allocated at compile-time. By compile-time I mean "int array[100]", which is different to allocation 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 that the C++ memory model is: all local non-static variables and arrays are allocated on the stack, and that each thread has its own stack. Is this true (ie. is this officially part of the standard) ?

like image 562
mtall Avatar asked Mar 05 '13 07:03

mtall


1 Answers

Such variables are allocated on the stack, and since each thread has its own stack, it is perfectly safe to use local arrays. They are not different from e.g. local ints.

like image 133
Oberon Avatar answered Oct 30 '22 05:10

Oberon