Thread Memory and Resources
9 min read
When multiple threads run inside the same C++ program, they work together inside a single process, yet each thread still needs its own private workspace to track function calls and local variables. Understanding how memory is divided between threads is the foundation for writing fast, bug-free concurrent code: it explains why sharing data between threads is so cheap, where data races come from, how the stack differs from thread_local, and why spawning too many threads exhausts system resources.
Private vs. Shared Memory
A crucial difference between running multiple processes and running multiple threads is how memory is organized. Processes are walled off from one another by the operating system; threads inside the same process live in the same address space.
- Private to each thread:
- Call stack: Every thread receives its own dedicated stack storing its local variables, function parameters, and return addresses (typically reserved as ~1 MB on Windows or ~8 MB on Linux by default). A local variable declared inside
doWork()int1is completely separate fromdoWork()’s local variable int2. - CPU state: Each thread has its own register state and instruction pointer so the OS can pause and resume it seamlessly.
- Thread-local storage (
thread_local): Variables declared with thethread_localkeyword get one independent copy per thread, managed in a dedicated Thread-Local Storage (TLS) segment.
- Call stack: Every thread receives its own dedicated stack storing its local variables, function parameters, and return addresses (typically reserved as ~1 MB on Windows or ~8 MB on Linux by default). A local variable declared inside
- Shared across all threads:
- Heap memory: Anything allocated dynamically (
new,std::make_unique,std::vectorbuffers) is visible to any thread that holds a pointer or reference to it. - Globals and statics: Global variables and
staticvariables exist once for the whole process. - Program code and OS handles: All threads execute from the same loaded instructions and share open files, sockets, and standard I/O streams.
- Heap memory: Anything allocated dynamically (
Sharing Common Data (and Data Races)
Because threads share common data directly in memory, passing information between them is blazingly fast, with no serialization or OS-level copying required. However, shared memory comes with a major catch: if two threads access the same variable at the same time and at least one of them writes to it without coordination, you get a data race, resulting in corrupted values or subtle, unpredictable bugs.
Coordinating reads and writes to shared heap or global data requires synchronization primitives such as std::mutex or std::atomic. By contrast, anything living strictly on a thread’s own stack or in thread_local storage is private by design and requires no synchronization.
Stack vs. thread_local
Both stack variables and thread_local variables are private to a single thread, so neither needs a mutex, yet they differ in lifetime and scope across function calls:
| Stack (local variable) | thread_local | Regular static / global | |
|---|---|---|---|
| How many copies? | 1 per function call | 1 per thread | 1 per process (shared) |
| Lifetime | Created on function entry, destroyed on return | Created once per thread, destroyed when the thread exits | Lives for the entire program |
| Persists across calls? | No | Yes (within the same thread) | Yes (across all threads) |
| Accessible anywhere on the thread? | Only in the current scope | Yes (if declared at namespace/class scope) | Yes (needs synchronization) |
Think of thread_local as “a global (or static) variable, except each thread gets its own private copy.”
For example, suppose a helper function is called thousands of times per thread and needs a random number generator:
Another classic real-world example is errno in C/C++: any library function running on t1 can set errno and your code on t1 can inspect it afterwards without passing it through every function parameter, while t2 maintains its own independent copy and can never overwrite t1’s error code.
Thread Limits and Resource Costs
The C++ standard does not impose a fixed limit on how many threads you can create. To understand practical limits, it helps to separate hardware concurrency from operating system threads:
- Hardware concurrency is the number of threads your CPU can physically execute at the exact same moment (for example, 8 cores / 16 logical threads). You can query this hint at runtime:
- Software (OS) threads can outnumber your CPU cores. When you spawn more threads than cores, the operating system rapidly switches between them (context switching), giving each thread small slices of CPU time. For I/O-heavy work (waiting on files or network responses), having more threads than cores can be helpful; for CPU-bound math, spawning far more threads than cores actually slows things down due to scheduling overhead.
Resource Exhaustion from Unbounded Threads
Threads are lightweight compared to full processes, but they are not free. Every OS thread requires:
- Stack memory reserved in virtual address space (typically 1 MB per thread on Windows and 8 MB by default on Linux).
- Kernel bookkeeping structures and scheduler entries maintained by the operating system.
If a bug causes your program to spawn threads in an infinite loop without joining or capping them, you will quickly hit the OS’s per-process thread limit or run out of virtual memory/RAM. When the OS refuses to create another thread, the std::thread constructor throws a std::system_error exception (typically resource_unavailable_try_again). Even before hitting the hard wall, thousands of competing threads can grind a machine to a halt through constant context switching and cache thrashing.
For this reason, production C++ applications rarely spawn unbounded threads per task. Instead, they reuse a fixed number of workers through a thread pool.
Comments
Clicking this button loads the comment box from
giscus.app(powered by GitHub Discussions). See our Privacy Policy.