__thread, multithread variables

Category

C++Builder keyword extensions

Description

The keyword __thread is used in multithread programs to preserve a unique copy of global and static class variables. Each program thread maintains a private copy of a __thread variable for each thread.

The syntax is Type __thread variable__name. For example

int __thread x;

declares an integer type variable that will be global but private to each thread in the program in which the statement occurs.

Using thread-local variables

The thread function and any of the routines it calls have their own local variables, just like any other C++ routines. These routines also can access any global variables. In fact, global variables provide a powerful mechanism for communicating between threads.
Sometimes, however, you may want to use variables that are global to all the routines running in your thread, but not shared with other instances of the same thread class. You can do this by declaring thread-local variables. Make a variable thread-local by adding the __thread modifier to the variable declaration. For example,

int __thread x;

declares an integer type variable that is private to each thread in the application, but global within each thread.

The __thread modifier can only be used for global (file-scope) and static variables. Pointer and Function variables can’t be thread variables. Types that use copy-on-write semantics, such as AnsiStrings don’t work as thread variables either. A program element that requires runtime initialization or runtime finalization cannot be declared to be a __thread type.

The following declarations require runtime initialization and are therefore illegal.

int f( );

int __thread x = f( ); // illegal

Instantiation of a class with a user-defined constructor or destructor requires runtime initialization and is therefore illegal:

class X {

X( );
~X( );
};
X __thread myclass; // illegal

Comments

  1. Very useful material
    http://tinyurl.com/6nlxohj
    http://tinyurl.com/bebgfmq

    ReplyDelete

Post a Comment

Popular posts from this blog

TClientDataSet::AppendData and TClientDataSet::BeforeGetRecords

OleVariant

Password Remover