RAD Studio
ContentsIndex
PreviousUpNext
Using Thread-local Variables

The thread function and any of the routines it calls have their own local variables, just like any other Dephi language 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 declaring it in a threadvar section (Delphi) or adding the __thread modifier (C++). For example,

threadvar
x : integer;

 

int __thread x;

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

The threadvar section can only be used for global variables. Pointer and Function variables can't be thread variables. Types that use copy-on-write semantics, such as long strings don't work as thread variables either. 

In C++, 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
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!