The following guidelines must be observed when declaring statically bound thread local objects and variables:
#define Thread __declspec( thread )
Thread void func(); // This will generate an error.
#define Thread __declspec( thread )
void func1()
{
Thread int tls_i; // This will generate an error.
}
int func2( Thread int tls_i ) // This will generate an error.
{
return tls_i;
}
#define Thread __declspec( thread )
extern int tls_i; // This will generate an error, since the
int Thread tls_i; // declaration and definition differ.
char __declspec( thread ) *ch; // Error
#define Thread __declspec( thread )
class Thread C // Error: classes cannot be declared Thread.
{
// Code
};
C CObject;
Because the declaration of C++ objects that utilize the thread attribute is permitted, the following two examples are semantically equivalent:
#define Thread __declspec( thread )
Thread class B
{
// Code
} BObject; // OK--BObject is declared thread local.
class B
{
// Code
};
Thread B BObject; // OK--BObject is declared thread local.
class tlsClass
{
private:
int x;
public:
tlsClass() { x = 1; } ;
~tlsClass();
}
__declspec( thread ) tlsClass tlsObject;
extern int func();
__declspec( thread ) int y = func();
In this case, data or objects initialized by the func
routine do not necessarily belong to the same thread into which tlsObject
is instantiated.
#define Thread __declspec( thread )
Thread int tls_i;
int *p = &tls_i; //This will generate an error in C.
This restriction does not apply in C++, however. Because C++ permits dynamic initialization of all objects, you can initialize an object with an expression that uses the address of a thread local variable. This is accomplished in the same way as the construction of thread local objects. For example, the code shown above will not generate an error when compiled as a C++ source file. Note that the address of a thread local variable is valid only as long as the thread in which the address was taken still exists.
#define Thread __declspec( thread )
Thread int tls_i = tls_i; // Error in C and C++
int j = j; // OK in C++, error in C
Thread int tls_i = sizeof( tls_i ) // Legal in C and C++
Note that a sizeof
expression that includes the object being initialized does not constitute a reference to itself, and is legal in both C and C++.
C++ does not allow such dynamic initialization of thread data because of possible future enhancements to the thread local storage facility.