Name
Threadvar Keyword
Syntax
threadvarName
=Type
; ...
Description
The threadvar
keyword starts a variable
declaration in the same manner as the var
keyword,
except that threadvar
can be used only at the unit
level. Variables declared using threadvar
have
distinct values in each thread. Ordinary variables, on the other
hand, are shared among all threads in a
process.
Tips and Tricks
If you are using the
TThread
class (Classes
unit), you will probably find it more convenient to use fields to store per-thread data.If you are writing a reusable subroutine or class that might be used in multiple threads, you can use
threadvar
variables to keep track of per-thread information.Threadvar
declarations apply only to the variable itself. If the variable is a pointer or encapsulates a pointer (e.g., object, long string, dynamic array,Variant
), the data might be accessible from multiple threads.Threadvar
variables use Windows thread-local storage (TLS). Every variable access requires a function call, so another reason to use theTThread
class is that access to the object’s fields is faster than usingthreadvar
variables.Every module that uses a
threadvar
variable requires a TLS slot, but Windows has a small number of TLS slots available. A large project should use packages to ensure the availability of this limited resource.Every module (application, DLL, package) that contains a
threadvar
variable needs its own, separate TLS slot. If you link a DLL statically, the DLL contains its own ...
Get Delphi in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.