16

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?

user5492770
  • 357
  • 3
  • 5
  • 13
  • `Why can't we pass the data ... as params to this function?` - Such a way you will have data **local** to given function, while TLS implements **global** data. Local and global data are *alternatives*, each has its own prop. and cons. – Tsyvarev Feb 29 '16 at 06:58
  • I've been writing mutithreaded apps for decades, not used teh 'globals for threads' TLS yet. It's surprising how many devs. are fine with 'globals are bad', but are happy to use TLS. – Martin James Feb 29 '16 at 09:12
  • 1
    For newcomers, I suggest reading Chapter *31: Threads: Thread Safety and Per-Thread Storage* of the *The Linux Programming Interface* book, you will get all your answers there. – Rick Apr 17 '19 at 08:50
  • @Rick Thanks for your recommend for this great book – yuanjianpeng Dec 22 '20 at 03:41

3 Answers3

9

Static and global data are shared across all the threads. If you modified a global/static variable it is visible to all the threads. Unlike global/shared variable if you create a variable in TLS, every thread has its own copy of the variable, i.e. changes to the variable is local to the thread. Unlike global variable where an access is made through ds segment, the TLS variable are accessed using (gs/fs) segment. A good way to learn about it is to look at the disassembly generated by the compiler.

Yogi
  • 446
  • 3
  • 9
6

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.

user3344003
  • 20,574
  • 3
  • 26
  • 62
6

We need thread-local storage to create libraries that have thread-safe functions, because of the thread-local storage each call to a function has its copy of the same global data, so it's safe I like to point out that the implementation is the same for copy on write technique.

in normal function with global data, the content of that data can be updated by multiple threads and make it unreliable, but in thread-local storage, you can think of it as

"global became local when multiple access happen "

zerocool
  • 3,256
  • 2
  • 24
  • 40