Thread-Local Storage TLS

Source: Internet
Author: User

1. Reasons for using thread-local storage
When we want the global variables of this process to become thread-private, instead of shared by all threads, that is, when each thread has a copy, the thread-local storage (tls,thread local Storage) mechanism can be used.

2. Dynamic TLS
(1) Call the TlsAlloc function
Two different ways:

1> Global Call once : Global_dwtlsindex=tlsalloc ();

If the program calls only once tlsalloc, not every thread calls the TlsAlloc () function, multiple threads use the same index value, and while different threads appear to be using the same name as the TLS array index variable, the actual threads may actually get different DWORD value. The implication is that each TLS-using thread obtains a thread-local static variable of type DWORD as an index variable of the TLS array .

each thread within the 2> process is called once :

Each thread gets a different index value, and debugging can see each call, and the size of the index value is incremented by 1.

function Flow:

1> The function retrieves the bit flags in the system process and finds a free flag , then changes the flag from free to InUse and returns the index in the in-place array, usually saving the index in a global variable. Because this value is used throughout the process, not in the thread range.
2> If TlsAlloc cannot find a free flag in the list, it returns tls_out_of_indexes.
before the function returns , the 3>tlsalloc function iterates through each thread in the process and sets the corresponding element to 0 in the TLS array of each thread, based on the newly allocated index.


(2) Call TlsSetValue (Dwtlsindex,pvtlsvalue)

Put a value into the array of threads
The function puts a pvoid value that Pvtlsvalue flags in the thread's array,dwtlsindex specifies the exact position in the array (obtained by TlsAlloc)
When a thread calls TlsSetValue, it modifies its own array. However, it cannot modify the value in the TLS array of another thread.
(3) Call pvoid TlsGetValue (Dwtlsindex)

Retrieving a value from an array of threads
Similar to TlsSetValue, the array that belongs to the calling thread is viewed in TlsGetValue
(4) Call TlsFree (Dwtlsindex)

Release the TLS element that you have already booked
This function resets the INUSE flag corresponding to the array of bit flags in the process back to the free
The function also sets the content of the element in all threads to 0.
Attempting to release a TLS element that has not been assigned will result in an error

DynamicTLS.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <windows.h> #include <process.h> #include <ctime> #include <cstdlib > #include <vector> #include <iostream>using namespace std;clock_t gc_begin = 0;clock_t gc_end = 0;clock_t g   C_interval = 0;       Global//unsigned long __stdcall ThreadProc (void *arg); createthreadunsigned int __stdcall ThreadProc (void *arg); int main (int argc, char *argv[]) {/* different threads appear to be using the same name as the TLS array index variable, But actually each thread may get a different DWORD value. The implication is that each TLS-using thread obtains a thread-local static variable of type DWORD as an index variable of the TLS array. *///here using Tlsalloca () can, call this function inside the thread can also, so that each of the threads have a different index value,//Just call here once, the implementation of the program is also successful, different threads use the same index value also succeeded//dword TlsIndex =    TlsAlloc (); After this step, the current thread actually accesses the copy version within the thread of the TLS array index variable//Here the first index value produced by calling TlsAlloc () is also 1DWORD tlsindex = 0;vector

  

Here, add the _beginthreadex () function and the CreateThread function when creating the thread, the thread that was created, the call to the TlsAlloc function to produce a different index value, the first index value of the thread under the _beginthreadex () function is 3, The first index value of the thread under the CreateThread function is 1, and the thread under the _beginthreadex () function takes up two bits for some reason:

The first index value of a thread under the CreateThread function:

The first index value of a thread under the _beginthreadex () function:

3. Static TLS
(1) Declaration of a static TLS variable
__declspec (thread) int number;
(2) The implementation principle of static TLS
For Windows systems, a global or static variable is normally placed in the ". Data" or ". BSS" segment, but when we use __declspec (thread) to define a thread-private variable, the compiler puts these variables in the ". TLS" segment of the PE file.


When the system starts a new thread, it allocates a sufficient amount of space from the process's heap and copies the contents of the ". TLS" segment into this space, so that each thread has its own separate ". TLS" copy . So for the same variable defined with __declspec (thread), they are not the same address in different threads.

  thread Environment block (teb,thread environment block). This structure holds information about the thread's stack address, thread ID, and so on, where a domain is a TLS array, and its offset in TEB is 0x2c. For each thread, the segment referred to by the FS segment Register of x86 is the teb of the thread, so that the address of the TLS array of the threads can be accessed through fs:[0x2c] .

Static_tls.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <windows.h> #include <iostream>//define a static TLS global variable __declspec (thread) int __ Tlsvalue = 0;using namespace Std;dword WINAPI threadprocedure (LPVOID parameterdata); int main () {    // Set the main thread static TLS value to 5__tlsvalue = 5; HANDLE threadhandle = CreateThread (null, 0, threadprocedure, NULL, 0, NULL); if (threadhandle) {// Wait until the child thread ends WaitForSingleObject (threadhandle, INFINITE);//Gets the value of the main thread static TLS cout << "main thread __tlsvalue=" << __ Tlsvalue << Endl;}    return 0;} DWORD WINAPI threadprocedure (lpvoid parameterdata) {//Set child thread value to 10, does not affect the main thread __tlsvalue = 10;//Gets the values of the child thread static TLS cout < < "sub-thread __tlsvalue=" << __tlsvalue << endl;return 0;}

  

Thread-Local Storage TLS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.