Linker and Libraries Guide

C/C++ Programming Interface

Variables are declared thread-local using the __thread keyword, as in the following examples:

__thread int i;
__thread char *p;
__thread struct state s;

During loop optimizations, the compiler may choose to create thread-local temporaries as needed.

Applicability

The __thread keyword may be applied to any global, file-scoped static, or function-scoped static variable. It has no effect on automatic variables, which are always thread-local.

Initialization

In C++, a thread-local variable may not be initialized if the initialization requires a static constructor. Otherwise, a thread-local variable may be initialized to any value that would be legal for an ordinary static variable.

No variable, thread-local or otherwise, may be statically initialized to the address of a thread-local variable.

Binding

Thread-local variables may be declared and referenced externally, and they are subject to the same interposition rules as normal symbols.

Dynamic loading restrictions

A shared library can be dynamically loaded during process startup, or after process startup via lazy loading, filters, or dlopen(3DL). A shared library containing a reference to a thread-local variable, may be loaded post-startup if every translation unit containing the reference is compiled with a dynamic TLS model.

Static TLS models generates faster code. However, code compiled to use this model cannot reference thread-local variables in post-startup dynamically loaded libraries. A dynamic TLS model is able to reference all TLS. These models are described in Thread-Local Storage Access Models.

Address-of operator

The address-of operator, &, can be applied to a thread-local variable. This operator is evaluated at runtime, and returns the address of the variable within the current thread. The address obtained by this operator may be used freely by any thread in the process as long as the thread that evaluated the address remains in existence. When a thread terminates, any pointers to thread-local variables in that thread become invalid.

When dlsym(3DL) is used to obtain the address of a thread-local variable, the address returned is the address of the instance of that variable in the thread that called dlsym().