Newbie Thread Programming

Allan_Fernandes
Allan_Fernandes used Ask the Experts™
on
I am using Threads programming for the first time.
Can use the below mentioned Private variable 'sysAbort' as done below ?
Can I use sysNum Local Variable as done below ?
(I will be running only one instance of the thread at a time)


  private
    { Private declarations }
    sysAbort:Boolean ;

procedure TForm3.button_StartClick(Sender: TObject);
var
  sysNum:Integer ;
begin
  sysAbort:=False ;
  sysNum:=0 ;
  memo1.lines.add('Starting') ;
  with TThread.CreateAnonymousThread(
    procedure
    var
      MaxValue:Int64 ;
      I: Integer;
      Total: Integer;
    begin
      MaxValue:=1000 ;
      for I := 1 to MaxValue do
      begin
        if sysAbort then  // Can I use thus ?
          break ;
        sysNum:=I ;  // Can I use local variable
        // memo1.lines.Add('Violated  ' + Inttostr(sysNum)) ;  // This works too !
        if (I * 10 mod MaxValue) = 0 then
          TThread.Synchronize (TThread.CurrentThread,
            procedure ()
            begin
              memo1.lines.Add('Progress : ' + Inttostr(I)) ;
            end);

        sleep(10) ;   // just for delay
      end;

      TThread.Synchronize (TThread.CurrentThread,
        procedure ()
        begin
          memo1.lines.Add('End of process : ' + IntToStr(sysNum));
        end);
    end

  ) do
  begin
    OnTerminate := ThreadFinished ;
    Start;
  end;
end;

procedure TForm3.ThreadFinished(Sender: TObject);
begin
  if TThread(Sender).FatalException = nil then begin
    TThread.Queue(nil,
      procedure
      begin
        memo1.lines.Add('Via Queue after Finish');
      end
    );
  end;
end;

procedure TForm3.button_AbortClick(Sender: TObject);
begin
  sysAbort:=True ;
end;

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software architect
Top Expert 2012
Commented:
This is not good approach, because checking sysAbort should be synchronized with main thread.
Something like:
...
with TThread.CreateAnonymousThread(
    procedure
    var
      MaxValue:Int64 ;
      I: Integer;
      Total: Integer;
      bLocalAbort: Boolean;
    begin
      MaxValue:=1000 ;
      for I := 1 to MaxValue do
      begin
        TThread.Synchronize (TThread.CurrentThread,
        procedure ()
        begin
          bLocalAbort := sysAbort;
        end);
      if bLocalAbort then ...

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial