Thread-local variables differ from other variables in certain crucial aspects. When applied to a thread-local object, the &
(address-of) operator is evaluated at runtime and returns the address of the current thread's variable. Since operator &
is evaluated at runtime, a thread-local object's address is not a constant. The address of a thread-local variable is stable for the lifetime of that thread. Such an address may be used freely during the variable's lifetime by any thread in the program. You may take the address of a thread-local variable and pass it to other threads. All addresses of thread-local variables are invalidated and may not be used once that thread has terminated.
Thread-local variables may be statically-initialized as would ordinary static variables. According to the latest proposal, dynamic initialization for thread-local objects and variables is also supported. In this respect, the C++0x thread-local proposal is a significant improvement over the existing, nonstandard __thread storage type that certain compilers support. Consider:
thread_local std::string s("hi");//dynamic initialization
thread_local int num=4; //static initialization
thread_local int num2=func(); //dynamic initialization
thread_local std::string* p; //static initialization
thread_local static char buf[MAX];//static initialization
Generally speaking, compilers that support thread-local storage as a nonstandard extension (see list below) will compile only the declarations that require static initialization whereas compilers supporting the C++0x thread_local
keyword will compile all of the declarations above, including those requiring dynamic initialization.
Currently, thread-local storage is already available as a nonstandard extension from the following vendors:
The thread-local storage type is one of several concurrency support components that are being added to C++0x these days, including synchronization objects, threads, condition variables, atomic types, and a new memory model. The C++0x type traits
library also includes a trait class for identifying objects with thread-local storage.