Search code examples
tthread

Delphi - Diff between Threadvar and thread private variable


In Delphi, what's the diff between the 'Threadvar' (private copy of a variable available to each thread) and a variable declared in Thread 'private' section like:

TMyThread = class (TThread)
private
  FValue: integer
...
end;

In later case also, each thread should have a separate copy of FValue.


Solution

  • In short: the FValue in your TMythread will in principle be accessible from all threads, but only if they somehow manage to get past the "private" wall. So its actually just a object field like any other object field.

    the threadvar however is more like a global variable, and accessible likewise. Except that each thread gets its own instance of the declared threadvar.

    a bit more background: The threadvar variable is "created" when the thread is "born" The starting thread does actually not even have to be started using the TThread class!. (eg you can start a new thread using a winapi system call)

    Quite a while ago I found this out the hard way because I created a memory leak and had a hard time finding out why. Also: you cannot initialize and finalize a threadvar in the initialization/finalization sections of the declaring unit . Even the internally used, reference counted strings and arrays will impose a memory leak when used as threadvar, and not explicitly nullified by the owning thread before the thread "dies".

    AFAIK you can't declare a threadvar inside a class. Maybe you can create a class threadvar , but I never tried/needed it.

    IMO there usually is "a better way" than using threadvar. Some good starting for using threads in delphi is the provided delphi parallel library, or the open source OmniThread library.