Eran Nahshon
Eran Nahshon

Reputation: 29

thread local storage, and thread variables

i have few questions about TLS, and how it differes from local variables, global variables and local variables.

  1. thread local variables are accessible only for the owner thread, and local variables are accessible only for the function?
  2. where the thread local variables are stored?
  3. when we will want to use thread local variables?
  4. what is the life time of thread local variable?
  5. is thread local variable exlusive to the thread?

in general, i can't get the the different between local variable and thread local variable.

Upvotes: 0

Views: 711

Answers (1)

Seva Alekseyev
Seva Alekseyev

Reputation: 61361

Local variables exist in a function. Once the function returns, they're gone. Thread variables exist on a thread; once the thread quits, they're gone. In terms of lifetime, you could say that TLV are equivalent to local variables of the thread startup function, except you don't have to explicitly pass the reference to them to the code further down.

Note that there are two ways of employing TLV in a native Windows program. Microsoft C++ has a __declspec(thread) modifier, and also there's a family of Windows API functions - TlsAlloc() and the like.

  1. Other threads can access thread local variables if a pointer/reference is somehow passed to them. However, the vanilla access methods will return the current thread's instance.

If you try to access it from another thread after the creating thread quits, that's undefined behavior.

  1. That's an implementation detail. But most likely, on the heap.

  2. Um, that's up to you. In theory, pretty much everything they normally do with TLV you can also do without...

  3. As long as the thread is running.

  4. Define "exclusive".

Upvotes: 1

Related Questions