RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Thanks for Not Sharing, Or, How to Define Thread-Local Data-3 : Page 3

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.

Dynamic Initialization
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.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date