AlgoMaster Logo

Thread-Local Storage (thread_local)

Last Updated: May 17, 2026

10 min read

Some pieces of state shouldn't be shared between threads, even when the variable lives at file or global scope. A request ID, a random number generator, a scratch buffer reused across calls, these are all per-thread by nature, and sharing them produces either incorrect results or a queue of threads contending on a mutex. The thread_local keyword, added in C++11, gives every thread its own independent copy of a variable, with a lifetime that matches the thread itself. This chapter covers how thread_local storage works, where it shines in everyday concurrent code, and the corner cases that trip people up.

Premium Content

Subscribe to unlock full access to this content and more premium articles.