Question

Given native code (C/C++), could someone explain thread local storage? Is it simply a trick that allows threads to control the lifetime of their own variables, or is there some isolation/protection enforcement by either the compiler or the hardware?

Does the underling platform matter?

Further more, what is the difference between plain TLS and "Fiber-safe" TLS, with respect to the above?

Sorry, I googled, but all I could find was how to use TLS (which I already know) but not the geeky details behind the scenes.

Was it helpful?

Solution

Thread-local Storage (TLS) is managed by the OS. Every thread object in the kernel contains a local array of TLS slots. At runtime, the app's code can call TlsAlloc() for each TLS variable it needs (such as for variables declared as __thread or __declspec(thread), depending on compiler) to reserve available indexes into the TLS array. Each thread can then use TlsGetValue() and TlsSetValue() to read/write values that are stored in the calling thread's TLS array at those indexes. When done using TLS, the app can call TlsFree() to release its reserved indexes.

For example, at app startup, the app calls TlsAlloc() once to reserve TLS index 0. Inside each thread that subsequently runs, any given thread can call TlsSetValue() for TLS index 0, and that value will be stored locally for that specific thread, thus values stored at TLS index 0 for other threads will not be affected.

Refer to MSDN for more details:

Thread Local Storage

Fibers run inside of threads. So multiple fibers running in the same thread will share the same TLS array for that thread. If one fiber sets a value at TLS index 0, all fibers running in that same thread are affected. Fiber-Safe TLS is just a compiler optimization that prevents a fiber from caching any TLS information, in case that fiber jumps from one thread to another during its lifetime.

OTHER TIPS

The quick answer: when a thread starts, the GS segment register points to a (mostly undocumented) OS data structure for that thread. One of the elements of this data structure is an array of 64 PVOID elements, used by the TLS functions to store up to 64 TLS variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top