Question

I create a thread

type 
  ss_thread = class;

  ss_thread = class(TThread)
  protected
    Fff_id : string;
    Fff_cmd : string;
    Fff_host : string;
    Fff_port : TIdPort;
    procedure Execute; override;
  public
    constructor Create(const ff_id, ff_cmd: string; ff_host: string; ff_port: TIdPort);
  end;

constructor ss_thread.Create(const ff_id, ff_cmd: string; ff_host: string; ff_port: TIdPort);
begin
  inherited Create(False);
  Fff_id   := ff_id;
  Fff_cmd  := ff_cmd;
  Fff_host := ff_host;
  Fff_port := ff_port;
end;

...
id := 123; // dynamic
...

nst_ss_thread.Create(id, cmd, host, port);

and doing something on

procedure ss_thread.Execute;
var
  ws : TIdTCPClient;
  data : TIdBytes;
  i : integer;
  list : TList;
begin
      ws := TIdTCPClient.Create(nil);
      ws.Host := Fff_host;
      ws.Port := Fff_port;
....

I have master thread, which receive data from other source, and I need to forward all data to my threads with ID i received to 'ws' IdTCPClient.

How to have a list of IdTCPClients of all my created threads ?

Thanks

Was it helpful?

Solution

Store them in a thread list.

ClientList: TThreadList<TIdTCPClient>;

Create one of these objects before you create any clients.

ClientList := TThreadList<TIdTCPClient>.Create;

Whenever you create a client, add it:

procedure ss_thread.Execute;
var
  List: TList<TIdTCPClient>;
....
ws := TIdTCPClient.Create(nil);
List := ClientList.LockList;
try
  List.Add(ws);
finally
  ClientList.UnlockList;
end;

Whenever you need to iterate over the clients, you can do so like this:

var
  List: TList<TIdTCPClient>;
  Client: TIdTCPClient;
....
List := ClientList.LockList;
try
  for Client in List do
    // do something with Client
finally
  ClientList.UnlockList;
end;

In the thread's destructor you will also need to remove the client from the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top