2

According to Microsoft's documentation MAXIMUM_WAIT_OBJECTS is 64 (the maximum of handles to wait for) but for some reason sometimes (because randomly) WaitForMultipleObjects returns WAIT_FAILED ($FFFFFFFF) and GetLastError returns ERROR_INVALID_HANDLE (6). What am I doing wrong?

procedure TForm1.Button1Click(Sender: TObject);
var ArrayOfHandles:array of THandle;
    Threads,x:byte;
    ReturnValue:Cardinal;
begin

  Threads:=64;
  SetLength(ArrayOfHandles,Threads);

  for x:=0 to Threads-1 do
  begin
    WorkerThread:= TWorkerThread.Create(True);
    ArrayOfHandles[x]:=WorkerThread.Handle;
    WorkerThread.FreeOnTerminate:=true;
    WorkerThread.Priority := tpNormal;
    WorkerThread.Resume;
  end;

  ReturnValue:=WaitForMultipleObjects(Threads,@ArrayOfHandles[0],false,INFINITE);
  ShowMessage('ReturnValue='+IntToStr(ReturnValue)+#13+'GetLastError='+IntToStr(GetLastError));

end;

procedure TWorkerThread.Execute;
begin

  sleep( Random(1000) );

end;
AmigoJack
  • 5,234
  • 1
  • 15
  • 31
Atak_Snajpera
  • 619
  • 9
  • 24

1 Answers1

3

Ok. I'm an idiot. This MUST be false!

WorkerThread.FreeOnTerminate:=false;
Atak_Snajpera
  • 619
  • 9
  • 24
  • This is no explanation. The reason is: after creating 64 threads and finally calling `WaitForMultipleObjects()` nobody can expect that **all** of those 64 threads are still running. If the threads are not expected to run forever this approach is wrong, as you now operate with corpses (those threads have still ended already) - you should come up with a different concept. – AmigoJack Nov 20 '21 at 17:07