views:

112

answers:

3

When you allocate some TLS for thread A in a slot, can you then access that same slot from Thread B?

Is it internally synchronized or how does that work?

+4  A: 

No, the whole point of thread local storage is that it's local to the thread - if you access the same slot in a different thread, you'll get the value for that thread instead of the other one.

If you need to share state between threads, don't use thread local storage.

Jon Skeet
But the array that has the TLS Slots is global, I'm not sure I understand how that can be? Or have I got it wrong...
Tony
@Tony - behind the scenes the OS takes care of ensuring that the slot points to different memory for different threads, as shown in your selecte answer. Even though the TLS variable is global, the actual value used will be distinct for each thread.
mdma
+2  A: 

The local variables of a function are unique to each thread that runs the function. This can be accomplished with help of TLS which as already mentioned is local for each thread. If you want to share some data between threads there are several options starting from using global or static variables up to memory mapped files and etc... also check thread synchronization if you need to share data between threads.

The following diagram illustrates how TLS works.

For more details check MSDN.

alt text

Incognito
Yes I get it, but your index vars are global... so they could be accessed by multiple threads??
Tony
Yes global or static variables are shared between multiple threads.
Incognito
+2  A: 

The terminology can be confusing because "slot" is often a metaphor for a memory location or a single place. With TLS, the slot is merely a "name" to a place in the thread's private storage. On x86/x84 there is no real thread local storage - all memory is global - so the system takes care of mapping each "slot" in TLS to a different actual memory location, according to the thread that is accessing it. Requests from the same thread for a slot result in the same memory location - accesses from different threads to the same slot results in different memory locations.

Synchronization is then not necessary since each thread is seeing different data. Unless of course you choose to store the same object in the TLS of two different threads, then that's a different story, but that's quite contrived case - the sharing is not because of TLS.

mdma