$linuxjunkies
>

thread-local storage

also: TLS, thread-specific storage, thread-local data

Memory storage that is private to each thread within a process, allowing multiple threads to maintain independent copies of the same variable without interference.

Thread-local storage (TLS) is a mechanism where each thread in a multi-threaded program gets its own isolated instance of a variable or data structure. This is useful when you need global-like access to data, but each thread must have its own copy to avoid race conditions and synchronization overhead.

For example, consider a web server handling multiple client requests concurrently. Each thread might use thread-local storage to keep track of the current user ID or request context without requiring locks:

thread_local int current_user_id;

void handle_request() {
  current_user_id = get_user();
  // Each thread has its own current_user_id
}

In Linux, TLS is typically implemented using compiler keywords like __thread (GCC/Clang), or via POSIX thread-specific data functions like pthread_key_create() and pthread_setspecific(). This avoids the need for mutexes or other synchronization primitives.

Related terms