Thread Local Storage (TLS)
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 (, , , and ). Win32 and the Visual C++ compiler now support statically bound (load-time) per-thread data in addition to the existing API implementation.
Thread Local Storage is implemented through the Win32 API layer and the compiler. For more information, see the Win32 API documentation for , , , and .
The Visual C++ compiler includes a keyword to make TLS operations more automatic, rather than through the API layer. This syntax is described in the next section, Compiler Implementation for TLS.
To support TLS, a new attribute, thread, has been added to the C and C++ languages and is supported by the Visual C++ compiler. This attribute is an extended storage class modifier, as described in the previous section. Use the __declspec keyword to declare a thread variable. For example, the following code declares an integer thread local variable and initializes it with a value:
__declspec( thread ) int tls_i = 1;