Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to use Thread Local Storage (TlsAlloc, TlsGetValue, ets) instead of local variables

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

like image 811
mateusz m Avatar asked Jun 11 '11 18:06

mateusz m


People also ask

Why do we need thread-local storage?

With thread local storage (TLS), you can provide unique data for each thread that the process can access using a global index. One thread allocates the index, which can be used by the other threads to retrieve the unique data associated with the index.

Is thread-local storage fast?

In that scenario, accesses to thread-local variables can be almost as fast as access to other variables, the only difference being an extra pointer dereference. Unfortunately, many PC applications require something more complicated.

Which of the following uses the concept of thread-local storage?

Thread Local Storage (TLS) is the method by which each thread in a given multithreaded process can allocate locations in which to store thread-specific data. Dynamically bound (run-time) thread-specific data is supported by way of the TLS API (TlsAlloc).

What is thread-local storage in C++?

Threads share the data of the process to which it belongs to. This data sharing provides one of the benefits of multithreaded programming. However, in some circumstances, each thread might need its own copy of certain data. Such data is called thread-local storage (or TLS).


2 Answers

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

like image 191
Karthik Balaguru Avatar answered Oct 22 '22 11:10

Karthik Balaguru


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!

like image 41
David Heffernan Avatar answered Oct 22 '22 11:10

David Heffernan