|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
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 (TlsAlloc, TlsGetValue, TlsSetValue, and TlsFree). Win32 and the Visual C++ compiler now support statically bound (load-time) per-thread data in addition to the existing API implementation.
API Implementation for TLS
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.
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;