C ++ - Where are thread_local variables stored?

I am trying to understand how the thread_local qualifier works and where is the actual variable stored? This is in C ++.

Say I have a class with several member variables. A class object is created on the heap, and the object is split between two threads. An appropriate locking mechanism is used to ensure that two threads do not stomp on a member variable at the same time.

There is a need for threads to track multiple items related to a stream. Therefore, I am going to create a thread_local variable in the same header file as the class declaration. As far as I understand, both threads will get their own copy of this variable, right? Where exactly is the local stream variable stored in memory? If a data segment, how exactly is the correct variable selected at runtime?

+5
source share
3 answers

1. As far as I understand, both threads will get their own copy of this variable, right?
Yes. Each thread receives its own copy of the thread_local variable.
2. Where exactly is the local stream variable stored in memory? If a data segment, how exactly is the correct variable selected at runtime?
thread_local is an implementation of the concept of local thread storage. TLS is implemented as a slot table with each stream object. Each thread has its own copy of the table. For example, for example, in the TLS version for Windows, this table is in the stream information block of the stream. When a global / static variable is declared as thread_local, it will be associated with the table slot of each thread with the same offset. When a thread accesses the thread_local variable and then uses the current thread context, it accesses its own copy of the thread variable associated with the table slot inside this thread object. Please check this link for more details on the implementation of TLS. https://en.wikipedia.org/wiki/Thread-local_storage

+2
source

In the case of 64-bit Windows, TLS can be obtained through the GS selector register using a separate physical address space for the thread (allocated during CreateThread ()), although Visual Studio can map TLS to the process / thread of the virtual address space, with each thread receiving a different one virtual address, since it represents a different physical address for each thread. You can look at the disassembled code by going to rand () using the debugger to find out how it accesses the seed, which is a TLS variable.

+2
source

In your descriptions, it sounds like you want to mark some non-static member var as thread_local. This is not allowed.

thread_local somewhat similar to static (global), but defined for each thread, while static is common to all threads

Each thread has its own memory ranges. for example, your own stack.

http://en.cppreference.com/w/cpp/language/storage_duration Referen

-1
source

Source: https://habr.com/ru/post/1271167/


All Articles