Thread Local Storage (TLS) is the mechanism by which each thread in a multithreaded process allocates storage for thread-specific data. In standard multithreaded programs, data is shared among all threads of a given process, whereas thread local storage is the mechanism for allocating per-thread data. For a complete discussion of threads, see Multithreading Topics, and see the API Programmer’s Reference in the Microsoft Win32® Software Development Kit.
The C and C++ languages include the extended storage-class attribute, thread. The thread attribute must be used with 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;
You must observe these guidelines when declaring thread local objects and variables:
#define Thread __declspec( thread )
Thread void func(); // Error
#define Thread __declspec( thread )
void func1()
{
Thread int tls_i; // Error
}
int func2( Thread int tls_i ) // Error
{
return tls_i;
}
#define Thread __declspec( thread )
extern int tls_i; // This generates an error, because the
int Thread tls_i; // declaration and the definition differ.
char __declspec( thread ) *ch; // Error
__declspec(thread) class X {
public:
int I; } x; // x is a thread object
X y; // y is not a thread object
Because the declaration of objects that use the thread attribute is permitted, these two examples are semantically equivalent:
#define Thread __declspec( thread )
Thread class B
{
// Code
} BObject; // Okay--BObject declared thread local.
class B
{
// Code
}
Thread B BObject; // Okay--BObject declared thread local.
#define Thread __declspec( thread )
Thread int tls_i = tls_i; // C and C++ error
int j = j; // Okay in C++; C error
Thread int tls_i = sizeof( tls_i ) // Okay in C and C++
Note that a sizeof expression that includes the object being initialized does not constitute a reference to itself and is allowed in C and C++.