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.
Do not create pointer- or
procedural-type thread variables, and do not use thread variables in
dynamically loadable libraries (other than packages).
Dynamic variables that are
ordinarily managed by the compiler, long strings, wide strings, dynamic arrays,
variants, and interfaces can 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. For example,
threadvar S:
AnsiString;
S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
...
S := ''; // free the memory used by S
(You can free a variant by setting it to Unassigned and an interface or dynamic array by setting it to nil.)
Package declarations and source files
线程局部(thread-local)变量,也叫线程(thread)变量,用于多线程应用程序。线程局部变量与全局变量相似,不同的是执行的每个线程获得线程局部变量的一个私有副本,该变量副本不能被其他线程反问。线程局部变量用threadvar代替var来声明。例如
threadvar X:
Integer;
线程局部变量声明具有下列特点:
·不能出现在过程或函数中。
·不能包括初始化。
·不能在说明中使用指示字absolute。
不要创建指针或程序型类型的线程变量,也不要在动态加载库(dynamically loadable libraries,有别于其他的包)中使用线程变量。
被编译器一般管理的动态变量,长串,宽串,动态数组,变体,以及接口,可以用threadvar声明,但编译器不会自动释放为执行的每个线程在堆中创建的内存。如果要在线程变量中使用这些数据,则有责任释放其内存。例如,
threadvar S:
AnsiString;
S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
...
S := ''; // 释放变量S使用的内存
(可以通过置变量的值为Unassigned来释放变体;通过置变量的值为nil来释放接口或动态数组。)