Implementation of Thread-local storage (TLS) in C/C++ (multithreading)
c, c++11, linux, memory, multithreading
Solution
TLS is implemented as a data array within each thread object. Each thread object has its own local copy of the array, and each array is the same size. When you declare a global/static variable as using TLS, it is associated with an index into those arrays (that is how the compiler/OS knows how many array slots to allocate). Thus, when you access the variable at runtime, you are really accessing the associated slot in the data array of the thread context that is accessing the variable.
TLS may be a new native feature in C++11, but it has been available in various OS APIs for a long time.
TLS is implemented on Windows using the Win32 API `TlsAlloc()`, `TlsGetValue()`, `TlsSetValue()`, and `TlsFree()` functions. Here is an overview of how it works: Thread Local Storage
Here is an overview of how TLS works on Linux: ELF Handling For Thread-Local Storage
Problem
I am trying to understand the implementation of `Thread-local storage (TLS)` type. Available in `C++11` as `thread_local` keyword or in `C` as `__thread` keyword. This wikipedia article says: Sometimes it is desirable that two threads referring to the same static or global variable are actually referring to different memory locations, thereby making the variable thread-local, a canonical example being the C error code variable `errno`. This is used for making `static` or `global` variables local to the threads, so that the other threads can't access them. My question is how are these variables stored in the memory so that it becomes local to a thread ? After all these are inherently global/static variables, what stops other threads from accessing them ? Are they kept in some special data segment?