Search code examples
c++stackstandards

Does the C++ Standard specify that every thread has its own stack?


From this question I learned that each thread has its own stack (which makes sense to me). To my understanding, each thread needs to store the "process-pointer", as well as for example some variables like the return adress, or when passing parameters.

I'd however like to know wether this implementation of the c++ codes behaviour is something specific to certain operating systems, or if this is the described behaviour in the standard. If it is, I'd like to know where to read it up (because I tried and failed).


Solution

  • The standard does not specify the existence of anything as low-level as a "stack" (though it does have a concept named "stack unwinding", so there's a clear expectation of how some things get implemented).

    What the standard does is specify the behavior of functions. When you call one function, it specifies that the local variables of that function spring into existence as they are declared, and that these objects are distinct from any other invocation of the same function (unless they're static). This is what allows recursion to work.

    This means that to implement function calling, the compiler must do something to make all of this work as the standard outlines. Using a stack is the de-facto standard implementation for it, but it's not specifically required by the standard.

    That the same function executing in different threads have local variables that are distinct from each other (again, unless they're static) is merely a consequence of the same thing that allows recursion to work.