C++ local variables and threads (not thread_local) C++ local variables and threads (not thread_local) multithreading multithreading

C++ local variables and threads (not thread_local)


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.


C++98 didn't say anything about threads. Programs otherwise written to C++98 but which use threads do not have a meaning that is defined by C++98. Of course, it's sensible for threading extensions to provide stable, private local variables to threads, and they usually do. But there can exist threads for which this is not the case: for instance processes created by vfork on some Unix systems, whereby the parent and child will execute in the same stack frame, since the v in vfork means not to clone the address space, and vfork does not redirect the new process to a different function, either.

In C++11, there is threading support. Local variables in separate activation chains in separate C++11 threads do not interfere. But if you go outside the language and whip out vfork or anything resembling it, then all bets are off, like before.

But here is something. C++ has closures now. What if two threads both invoke the same closure? Then you have two threads sharing the same local variables. A closure is like an object and its captured local variables are like 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 thread can also simply pass the address of its local variables to another thread, thereby causing them to become shared.