title: How to wait for multiple threads to terminate in delphi?
body: <p>I have an application with 50 threads that do something and I want my procedure (btnTestClick) to wait until all threads are terminated. I've tried with global variable as counter and with <code>WaitForMultipleObjects(threadCount, @threadArr, True, INFINITE);</code> but the procedure never waits for all threads to terminate.Here is how my thread looks like :</p>
  
  <pre><code>TClientThread = class(TThread)
    protected
      procedure Execute; override;
  public
    constructor create(isSuspended : Boolean = False);
  end;
  </code></pre>
  
  <p>And here are the <strong>constructor</strong> and the <strong>execute</strong> procedure :</p>
  
  <pre><code>constructor TClientThread.create(isSuspended : Boolean);
  begin
    inherited Create(isSuspended);
    FreeOnTerminate := True;
  end;
  
  procedure TClientThread.Execute;
  var
  begin
    inherited;
    criticalSection.Enter;
    try
      Inc(globalThreadCounter);
    finally
      criticalSection.Leave;
    end;
  end; 
  </code></pre>
  
  <p>And my OnButtonClick is this :</p>
  
  <pre><code>procedure TMainForm.btnTestClick(Sender: TObject);
  var
    clientThreads : array of TClientThread;
    i, clientThreadsNum : Integer;
  begin
    clientThreadsNum := 50;
    SetLength(clientThreads, clientThreadsNum);
    for i := 0 to Length(clientThreads) - 1 do begin // РЕДАКТИРАЙ !!
      clientThreads[i] := TClientThread.Create(True);
    end;
    // here I will assign some variables to the suspended threads, but that's not important here 
    for i := 0 to Length(clientThreads) - 1 do begin
      clientThreads[i].Start;
    end;
  
    WaitForMultipleObjects(clientThreadsNum, @clientThreads, True, INFINITE);
    // do something after all threads are terminated 
  end;
  </code></pre>