/* Declaration of an integer thread local variable and its initialization: */ __thread int tlsVar1 = 1; static __thread int tlsVar2 = 100;
/* Declaration of a thread local function: */ __thread void func(); // Error
/* Declaration of an integer thread local variable and its initialization: */ __thread int tlsVar1 = 1; static __thread int tlsVar2 = 100;
/* Declaration of a thread local variable with an
automatic storage duration */
void
func1()
{
__thread int tlsVar; // Error
}
int
func2( __thread int tlsVar ) // Error
{
return tlsVar;
}
auto __thread float tlsVar; // Error
/* Mismatch in declaring and defining a thread local object either in the same file or in separate files: */ extern int tlsVar; // This is not allowed since the declaration __thread int tlsVar; // and the definition differ.
/* Initializing the thread local object by the class constructor: */
class tlsClass
{
public:
tlsClass() { x = 1; } ;
~tlsClass();
private:
int x;
}
__thread tlsClass tlsObject;
extern int func();
__thread int y = func();
/* Declaring a C++ class with a thread attribute: */
__thread class C // Error
{
. . .
};
C CObject;
/* Declaring a C++ class object with a thread attribute.
Because the declaration of C++ objects that use the thread
attribute is permitted, these two examples are semantically
equivalent: */
__thread class B
{
. . .
} BObject;
class B
{
. . .
}
__thread B BObject;
/* Initializing a pointer by the address of the thread local variable: */ __thread int tlsVar; int *p = &tlsVar; // C Error, NOT a C++ error
extern __thread int _Import i: /* error */
Statically declared __thread data objects can be used only in statically loaded files. This fact makes it unreliable to use TLS in a DLL, unless you know that the DLL (or anything statically linked to it) will never be loaded dynamically. In particular, do not attempt to use __thread data objects in DLLs that will be dynamically loaded through the LoadLibrary API. This restriction does not apply to dynamically loaded DLLs that use the thread-local-storage APIs.
![]()
Multithreaded Applications
Thread Local Storage