0

I am trying to understand how the TLS works, but I think that the definitions provided by Wikipedia and MSDN are different.

By reading the Wikipedia page, my understanding is that TLS is a way to map data which normally would be global/static locally for each thread of a process. If this is true, different threads cannot access to the data of other threads, though.

According MSDN: "One thread allocates the index, which can be used by the other threads to retrieve the unique data associated with the index", so it looks like that a thread can have access to the data of other threads.

Which seems to be in contrast of what Wikipedia says, where's the catch?

badnack
  • 737
  • 1
  • 11
  • 20

1 Answers1

0

Two confusions here:

  • Firstly, you allocate a (unique) TLS ID. Using that ID with the according function, every thread can access its associated TLS data. Note that this ID has to be allocated once but that the ID (not the data!) is used by all threads.
  • Every thread can access every other thread's data, whether it's TLS or not. The simple reason is that threads share a memory space (the memory space and the threads roughly make up a process). Getting at some other thread's TLS data is more difficult though, but a thread could e.g. pass a pointer.

In short, TLS works like a C++ map. The key is the pair of thread ID and TLS ID. The data is typically a pointer which can be used to indirectly reference some data. When accessing an element, you only supply the TLS ID, the implementation adds the calling thread's ID to form the key for lookup. Needless to say, access to that map is of course thread-safe.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
  • So assuming that thread_1 has the key of an object another thread linked in its TLS, thread_1 can modify it, right? – badnack Mar 18 '15 at 00:08
  • Depends on what kind of key you mean. Unfortunately I used that term in two different contexts in my response, but that should be fixed now. – Ulrich Eckhardt Mar 18 '15 at 06:30