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

alpiresAsked:
Who is Participating?
 
huferryConnect With a Mentor Commented:
Just in case you use an old Delphi (version 7) that does not support for-in....
procedure TForm1.StartLogin;
var
  I: Integer;
begin
  for I := 0 to Length(FLoginThreads)-1 do
  begin
    TMyThread(FLoginThreads[I]).Resume;
  end;
  FLoginThreads := nil;
end;

Open in new window

0
 
ThievingSixCommented:
Put "MyLogin;" in the execute method of the thread?
0
 
huferryCommented:
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

0
 
alpiresAuthor Commented:
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 ?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.