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
TThreadclass (Classesunit), 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
threadvarvariables to keep track of per-thread information.Threadvardeclarations 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.Threadvarvariables use Windows thread-local storage (TLS). Every variable access requires a function call, so another reason to use theTThreadclass is that access to the object’s fields is faster than usingthreadvarvariables.Every module that uses a
threadvarvariable 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
threadvarvariable needs its own, separate TLS slot. If you link a DLL statically, the DLL contains its own ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access