Link to home
Start Free TrialLog in
Avatar of alpires
alpiresFlag for Brazil

asked on

Accessing all threads instantiated

Hi Experts,

I have a thread:

TMythread = class(TThread)
  private
   
  protected
     procedure Execute; override;
     procedure MyLogin;
  public
     constructor Create(login:string);
  end;


In form1:

var
  Form1: TForm1;
  FTMyThread: TMythread;


SoI I run several threads:

eg:

FTMythread:=TMythread('login1');
FTMythread:=TMythread('login2');
FTMythread:=TMythread('login3');


In main thread (form1) i need execute all "MyLogin" procedures of mythreads instantiated, how to do this ?

Thx
Alexandre
Brazil

Avatar of ThievingSix
ThievingSix
Flag of United States of America image

Put "MyLogin;" in the execute method of the thread?
Look at the code below..
You'll need to hold the reference to each thread using different variables, to do this you can use an array.
This array should be filled with the thread instances (you can do this on OnCreate event). Assuming that the threads are started suspendedly (does not start until Resume is called), you can start the thread any time using the StartLogin method. This method will iterate through all threads on the array and run it one by one, after that it will empty the array (so that if StartLogin is called again, it does not give an access violation).
type
  TMyThread = ...
  ..
  end;
 
  TMyThreadArray = array of TMyThread;
 
  TForm1 = class(TForm)
  ..
  private
    FLoginThreads: TMyThreadArray;
    procedure StartLogin;
  ..
  ..
  end;
 
..
..
procedure TForm1.Form1Create(Sender: TObject);
begin
  SetLength(FLoginThreads, 3);
  FLoginThreads[0] := TMyThread.Create('login1');
  FLoginThreads[1] := TMyThread.Create('login2');
  FLoginThreads[2] := TMyThread.Create('login3');
end;
 
procedure TForm1.StartLogin;
var
  MyThread: TMyThread;
begin
  for MyThread in FLoginThreads do
  begin
    MyThread.Resume;
  end;
  FLoginThreads := nil;
end;

Open in new window

Avatar of alpires

ASKER

ok I understood, but in the line "for MyThread in FLoginThreads do" the following error occurs:

"operator not applicable to this operand type"

why this occurs ?
ASKER CERTIFIED SOLUTION
Avatar of huferry
huferry
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial