IBM extension

The __thread storage class specifier

The __thread storage class marks a static variable as having thread-local storage duration. This means that in a multi-threaded application a unique instance of the variable is created for each thread that uses it and destroyed when the thread terminates. The __thread storage class specifier can provide a convenient way of assuring thread-safety; declaring an object as per-thread allows multiple threads to access the object without the concern of race conditions while avoiding the need for low-level programming of thread synchronization or significant program restructuring.

Note:
In order for the __thread keyword to be recognized, you must compile with the LANGLVL(*EXTENDED) option. See LANGLVL in the ILE C/C++ Compiler Reference for details.

The specifier can be applied to any of the following:

It cannot be applied to block-scoped automatic variables or non-static data members.

The specifier can appear on its own, or preceded immediately by either the static or extern specifier, as in the following examples:

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

Variables marked with the __thread specifier can be initialized or uninitialized. C++ only __thread variables must be initialized with a constant expression and must not have a static constructor.

Applying the address-of operator (&) to a thread-local variable returns the runtime address of the current thread's instance of the variable. That thread can pass this address to any other thread but when the first thread terminates any pointers to its thread-local variables become invalid.

Related information

End of IBM extension


[ Top of Page | Previous Page | Next Page | Contents | Index ]