my question is why use TLS mechanism instead of just local variables in a thread function? Can you please provide some fine example, or what's the advantage of TLS over local vars? Thank you, Mateusz
5 Answers
If you can use local variables then do so and you invariably can use locals. Only as a last resort should you use thread local storage which suffers from almost all the same disadvantages as global variables. Although you are looking for a reason to use thread local storage, in fact best practice is to search for ways to avoid it!

- 601,492
- 42
- 1,072
- 1,490
Here is good link from Intel on using Thread-local Storage to Reduce Synchronization : https://software.intel.com/en-us/articles/use-thread-local-storage-to-reduce-synchronization

- 7,424
- 7
- 48
- 65
-
3I skipped this post but read this article later. Bad move, good article! – Seralize Nov 20 '14 at 15:28
TLS is helpful for things like user session context information which is thread specific, but might be used in various unrelated methods. In such situations, TLS is more convenient than passing the information up and down the call stack.

- 1,554
- 8
- 10
-
when I have a number of functions called from a thread function and they all use the same data then I use TLS just not to pass the data through the stack, yes? – mateusz m Jun 11 '11 at 18:18
-
1Yes. For example, if it's required at various points in the code to know the logged in user, it's easier to store that information in TLS within a singleton rather than pass the logged in user into every method. – btreat Jun 11 '11 at 18:21
-
1your understanding is correct but parsing on the stack is much better – David Heffernan Jun 11 '11 at 18:21
-
3I agree that the number of practical use cases for TLS is small and other alternatives should be explored first. However, I would say that using TLS for data common to all methods executed by a thread is preferable to modifying hundreds of method signatures to pass that data around. – btreat Jun 11 '11 at 18:29
I know one very good example of using TLS. When you are implementing LIBC or porting one of the LIBC variants to new platform you need somehow 'errno' variable (which on single threaded platfrom is just extern int errno) to be unique for each thread. LIBC functions simply stores it in TLS of the current thread and a call to errno just reads it from TLS. TLS is the way to make any library thread safe. You store any kind on 'static' or 'global' data in TLS so the same function being called from another thread will not corrupt your 'static' or 'global' variables in another thread. Which makes you functions re entrant from different threads.

- 459
- 5
- 8
Thread-local storage can be used to emulate global or static variables on a per-thread basis. "Normal" local variables can't.
-
1and what it gives me to have a global variable that is thread specific ? – mateusz m Jun 11 '11 at 18:15
-