Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is thread local storage? Why we need it?

I am reading the Threads in OS concepts and i come across "thread local storage (TLS)". What I understood is that the TLS is similar to static or global data, but it is more unique to individual thread. Its bit confusing on what is unique here?

Why can't we pass the data through runner (i.e., thread's actual codes) functions as params to this function?

like image 354
user5492770 Avatar asked Feb 29 '16 04:02

user5492770


People also ask

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).

What is thread-local storage (TLS)?

Such data is called thread-local storage (or TLS). For example, in a transaction-processing system, we might service each transaction in a separate thread. Each transaction might be assigned a unique identifier. To associate each thread with its unique identifier, we could use thread-local storage. It is easy to puzzle TLS with local variables.

How do I get the value of a thread-local storage table?

Each thread has its own copy of the thread-local storage table. Hence, each thread can independently use TlsSetValue (index) and obtain the specified value via TlsGetValue (index), because these set and look up an entry in the thread's own table.

What is thread local variable in Java?

In Java, thread-local variables are implemented by the ThreadLocal class object. ThreadLocal holds variable of type T, which is accessible via get/set methods. At least for Oracle/OpenJDK, this does not use native thread-local storage in spite of OS threads being used for other aspects of Java threading.


1 Answers

Let's supposed you are working in Ada. In your Ada program you define a task (thread) that includes a [static] variable that can only be accessed by the task. You now create multiple instances of your task. Then you need a copy of that [static] variable for each task.

That's where your implementation could use Thread Local Storage. In other words, it is a static area of memory that gets copied for each thread in a program.

As an alternative to TLS, a thread could allocate such storage at the top of the stack.

like image 173
user3344003 Avatar answered Dec 03 '22 15:12

user3344003