A somewhat less known feature of Delphi is thread variables. Thread variables are variables that can contain a different value for each thread in the application. They are defined like regular variables, the only difference is that the “var” keyword is replaced with “threadvar”. In the example below I’ll show you how they work in a small console application. Note that I used the TThread class for convenience, however in reality you’ll only ever need this for procedural code as you can add fields to your TThread subclass to store data in for each thread. The example uses the main thread and a separated thread to show you how it works.
program ThreadVarTest; {$APPTYPE CONSOLE} uses SysUtils, Classes; type TTestThread = class(TThread) protected procedure Execute; override; public constructor Create; end; threadvar TestVar: string; var i: Integer; procedure Test; begin WriteLn('Original TestVar: ' + TestVar); TestVar := 'Asdf' + IntToStr(i); Inc(i); WriteLn('New TestVar: ' + TestVar); end; { TTestThread } constructor TTestThread.Create; begin inherited Create(False); FreeOnTerminate := True; end; procedure TTestThread.Execute; begin Test; end; begin i := 0; Test; WriteLn('Starting thread.'); TTestThread.Create; ReadLn; WriteLn(TestVar); ReadLn; // Prevent window from closing end.
As you can see when running it, even though the content of the thread variable was changed, the variable was still empty when accessed by the new thread. I’ve added the incremental number to show you that when after you press a key when the thread has exited and you check the thread variable content for the main thread, it will show Adsf0 as it was stored by the main thread originaly.