1

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.

NamoRamana
  • 57
  • 7
  • see https://stackoverflow.com/questions/5180933/what-is-the-difference-between-a-threadvar-and-a-local-variable for a related discussion – Dave Novo Feb 07 '19 at 06:45

1 Answers1

1

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.

H.Hasenack
  • 1,094
  • 8
  • 27
  • @H.Hasenback - Thanks for your answer. Just want to confirm my understanding of your answer.. So let's say I have 2 instances of TMyThread - MyThread1 and MyThread2.. The "private" FValue pertaining to each thread instance will be accessible to the respective instances only. It means, MyThread1 will not be able to change the MyThread2.FValue, and vice versa, since Fvalue is declared "private". Right? – NamoRamana Jan 18 '19 at 20:51
  • Yeah, in principle that's right. Unless provide a link between the two instances... Just as an example: Imagine a field FOtherThread:TMyThread. This would allow one TMyThread object to reach another TMyThread object through something like FOtherThread.FOtherThread:=self from eg the constructor. – H.Hasenack Jan 22 '19 at 16:09