IT lexicon › Programming › Thread-local storage (TLS)

Thread-local storage (TLS)

Programming På svenska → Updated: 2026-11-06

Global variables where each thread gets its own copy — and the compiler, linker and ABI have to agree on how to find it.

In source code it takes a single keyword: thread_local in C++11, _Thread_local in C11, or GCC's older __thread. The classic case is errno, which stopped being an ordinary global once threads became routine. On x86-64 Linux the fs segment register points at the current thread's control block, and the variables sit at known offsets from it.

The hard part is shared libraries loaded late. The ELF scheme, documented by Ulrich Drepper in the early 2000s, therefore defines four access models. General dynamic always works but goes through a call to __tls_get_addr; local exec, inside the main executable, is a single instruction. The linker may downgrade the model when it can prove that's safe — one of the few places where the linker actively makes code faster.

← Back to the lexicon