Go to main content
Oracle® Developer Studio 12.6: C++ User's Guide

Exit Print View

Updated: July 2017
 
 

4.2 Thread-Local Storage

Take advantage of thread-local storage by declaring thread-local variables. A thread-local variable declaration consists of a normal variable declaration with the addition of the declaration specifier __thread. For more information, see -xthreadvar[=o].

The __thread keyword is recognized without the -features=extensions option. In C++11 mode, the __thread keyword is equivalent to the C++11 thread_local keyword.

You must include the __thread specifier in the first declaration of the thread variable. Variables that you declare with the __thread specifier are bound as they would be without the __thread specifier.

In C++03 or -compat=5 mode, you can declare variables only of static duration with the __thread specifier. Variables with static duration include file global, file static, function local static, and class static member. You should not declare variables with dynamic or automatic duration with the __thread specifier. A thread variable can have a static initializer, but it cannot have a dynamic initializer or destructors. For example, __thread int x = 4; is permitted, but __thread int x = f(); is not. A thread variable should not have a type with non-trivial constructors and destructors. In particular, a thread variable may not have type std::string.

In C++11 mode, you can declare variables of automatic duration with the __thread or thread_local specifier. Dynamic initialization of thread-local variables is supported.

The address-of operator (&) for a thread variable is evaluated at runtime and returns the address of the current thread’s variable. Therefore, the address of a thread variable is not a constant.

The address of a thread variable is stable for the lifetime of the corresponding thread. Any thread in the process can freely use the address of a thread variable during the variable’s lifetime. You cannot use a thread variable’s address after its thread terminates. All addresses of a thread’s variables are invalid after the thread’s termination.