Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Delphi threadvar work for Parallel.For?

Tags:

delphi

from here it says

"The ThreadVar keyword starts a set of variable definitions that are used by threads. Each thread is given a separate instance of each variable, thereby avoiding data conflicts, and preserving thread independence. "

So can I use in Parallel.For like this?

threadvar
    threadID: integer;

procedure TForm5.Button1Click(Sender: TObject);
var
 Tot: Integer;
begin
 TParallel.For(1, Max, procedure (I: Integer)
   begin
     threadID := i;  // each thread gets its own threadID?
     if IsPrime (threadID) then
       TInterlocked.Increment (Tot);
   end);
end;
like image 478
justyy Avatar asked Feb 01 '17 10:02

justyy


1 Answers

You can certainly use threadvar with PPL code. Internally the PPL code stands on top of the system threading libraries, and so threadvar works as you would expect.

like image 122
David Heffernan Avatar answered Oct 20 '22 15:10

David Heffernan