Why use local thread storage (TlsAlloc, TlsGetValue, ets) instead of local variables

My question is: why use the TLS mechanism instead of local variables in a stream function? Can you provide some great example or what is the advantage of TLS over local vars? Thank you Mateus

+8
multithreading thread-local-storage storage local
source share
5 answers

TLS is useful for things like user session context information, which is thread specific, but can be used in various unrelated methods. In such situations, TLS is more convenient than transferring information up and down the call stack.

+4
source share

If you can use local variables, then do it, and you can always use locals. Only as a last resort should you use a local thread store, which has almost all the same drawbacks as global variables. While you're looking for a reason to use local thread storage, it's actually best to look for ways to avoid this!

+7
source share

Here is a good reference from Intel on the use of Thread-local Storage to reduce synchronization: https://software.intel.com/en-us/articles/use-thread-local-storage-to-reduce-synchronization

+3
source share

I know one very good example of using TLS. When you implement LIBC or port one of the LIBC variants to a new platform, you need the "errno" variable (which on one platfrom stream is simply extern int errno) will be unique for each stream. LIBC functions simply store it in the TLS of the current thread, and errno just reads it from TLS. TLS is a way to make any library stream safe. You save any data on โ€œstaticโ€ or โ€œglobalโ€ data in TLS, so the same function called from another thread will not damage your โ€œstaticโ€ or โ€œglobalโ€ variables in another thread. This makes you a reseller from different streams.

+2
source share

Stream local storage can be used to emulate global or static variables for each stream. "Normal" local variables cannot.

+1
source share

All Articles