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.

Threads inside a C++ process share code, globals, and heap memory while keeping private call stacks, CPU registers, and thread_local storage.
Threads inside a C++ process share code, globals, and heap memory while keeping private call stacks, CPU registers, and thread_local storage.
  • 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() in t1 is completely separate from doWork()’s local variable in t2.
    • 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 the thread_local keyword get one independent copy per thread, managed in a dedicated Thread-Local Storage (TLS) segment.
  • Shared across all threads:
    • Heap memory: Anything allocated dynamically (new, std::make_unique, std::vector buffers) is visible to any thread that holds a pointer or reference to it.
    • Globals and statics: Global variables and static variables 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.

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_localRegular static / global
How many copies?1 per function call1 per thread1 per process (shared)
LifetimeCreated on function entry, destroyed on returnCreated once per thread, destroyed when the thread exitsLives for the entire program
Persists across calls?NoYes (within the same thread)Yes (across all threads)
Accessible anywhere on the thread?Only in the current scopeYes (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:

#include <random>

int nextRandom() {
    // Stack: recreated & re-seeded on EVERY call (slow, broken sequence)
    // static: ONE shared generator across all threads (data race!)
    // thread_local: ONE persistent generator per thread (fast & thread-safe)
    thread_local std::mt19937 rng(std::random_device{}());
    return rng();
}

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.

A single thread's view of memory: call stack frames are pushed and popped on every function call, thread_local variables persist in TLS for the thread's lifetime, and globals/heap remain shared across the entire process.
A single thread's view of memory: call stack frames are pushed and popped on every function call, thread_local variables persist in TLS for the thread's lifetime, and globals/heap remain shared across the entire process.

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:
unsigned int cores = std::thread::hardware_concurrency();
  • 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:

  1. Stack memory reserved in virtual address space (typically 1 MB per thread on Windows and 8 MB by default on Linux).
  2. 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.