Thread-local Variables Thread-local (or thread) variables are used in multithreaded applications. A thread-local variable is like a global
variable, except that each thread of execution gets its own private copy of the variable, which cannot be accessed
from other threads. Thread-local variables are declared with threadvar instead of var. For example,
threadvar X: Integer;
Thread-variable declarations
cannot occur within a procedure or function.
cannot include initializations.
cannot specify the absolute directive.
Dynamic variables that are ordinarily managed by the compilerlong strings, wide strings, dynamic arrays, variants,
and interfacescan be declared with threadvar, but the compiler does not automatically free the heap-allocated
memory created by each thread of execution. If you use these data types in thread variables, it is your responsibility
to dispose of their memory from within the thread, before the thread terminates. For example,
threadvar S: AnsiString;
S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
...
S := ''; // free the memory used by S
Note: Use of such constructs is discouraged.
You can free a variant by setting it to
Unassigned
and an interface or dynamic array by setting it to nil.
103