在阻塞主线程中使用TEvent和MsgWaitForMultipleObjects

问题描述

我找到了雷米有趣的代码Delphi : How to create and use Thread locally?

是否可以这样做,以便我可以执行多个线程并等待它们全部完成,然后继续执行主线程?我这样尝试过,但没有成功...

procedure Requery(DataList: TStringList);
var
  Event: TEvent;
  H: THandle;
  OpResult: array of Boolean;
  i: Integer;
begin
  Event := TEvent.Create;
  try
    SetLength(OpResult,DataList.Count); 
    for i:=0 to DataList.Count-1 do begin
      TThread.CreateAnonymousThread(
        procedure
        begin
          try
            // run query in thread
            OpResult[i]:=IsMyValueOK(DataList.Strings[i]);
          finally
            Event.SetEvent;
          end;
        end
      ).Start;
      H := Event.Handle;
    end;
    while MsgWaitForMultipleObjects(1,H,False,INFINITE,QS_ALLINPUT) = (WAIT_OBJECT_0+1) do Application.ProcessMessages;
    
    for i:=Low(OpResult) to High(OpResult) do begin
      Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i],True));
    end;
  finally
    Event.Free;
  end;

  // Do next jobs with query
  ...
end;

解决方法

可以做到这一点,这样我就可以做多个线程并等待它们全部完成

是的。您只需要创建多个TEvent对象,每个TThread一个,然后将它们的所有Handle存储在一个数组中以传递给MsgWaitForMultipleObjects()

procedure Requery(DataList: TStringList);
var
  Events: array of TEvent;
  H: array of THandle;
  OpResult: array of Boolean;
  i: Integer;
  Ret,Count: DWORD;

  // moved into a helper function so that the anonymous procedure
  // can capture the correct Index...
  procedure StartThread(Index: integer);
  begin
    Events[Index] := TEvent.Create;
    TThread.CreateAnonymousThread(
      procedure
      begin
        try
          // run query in thread
          OpResult[Index] := IsMyValueOK(DataList.Strings[Index]);
        finally
          Events[Index].SetEvent;
        end;
      end
    ).Start;
    H[Index] := Events[Index].Handle;
  end;

begin
  if DataList.Count > 0 then
  begin
    SetLength(Events,DataList.Count);
    SetLength(H,DataList.Count);
    SetLength(OpResult,DataList.Count);

    try
      for i := 0 to DataList.Count-1 do begin
        StartThread(i);
      end;

      Count := Length(H);
      repeat
        Ret := MsgWaitForMultipleObjects(Count,H[0],False,INFINITE,QS_ALLINPUT);
        if Ret = WAIT_FAILED then RaiseLastOSError;
        if Ret = (WAIT_OBJECT_0+Count) then
        begin
          Application.ProcessMessages;
          Continue;
        end;
        for i := Integer(Ret-WAIT_OBJECT_0)+1 to High(H) do begin
          H[i-1] := H[i];
        end;
        Dec(Count);
      until Count = 0;

      for i := Low(OpResult) to High(OpResult) do begin
        Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i],True));
      end;
    finally
      for i := Low(Events) to High(Events) do begin
        Events[i].Free;
      end;
    end;
  end;

  // Do next jobs with query
  ...
end;

话虽如此,您也可以摆脱TEvent对象,而等待TThread.Handle。线程的Handle完全终止后,将发出信号等待操作。唯一的陷阱是TThread.CreateAnonymousThread()创建了一个TThread属性为FreeOnTerminate的{​​{1}},因此您必须手动将其关闭:

True

无论哪种方式,请注意,procedure Requery(DataList: TStringList); var Threads: array of TThread; H: array of THandle; OpResult: array of Boolean; i: Integer; Ret,Count: DWORD; // moved into a helper function so that the anonymous procedure // can capture the correct Index... procedure StartThread(Index: integer); begin Threads[Index] := TThread.CreateAnonymousThread( procedure begin // run query in thread OpResult[Index] := IsMyValueOK(DataList.Strings[Index]); end ); Threads[Index].FreeOnTerminate := False; H[Index] := Threads[Index].Handle; Threads[Index].Start; end; begin try SetLength(Threads,DataList.Count); for i := 0 to DataList.Count-1 do begin StartThread(i); end; Count := Length(H); repeat Ret := MsgWaitForMultipleObjects(Count,QS_ALLINPUT); if Ret = WAIT_FAILED then RaiseLastOSError; if Ret = (WAIT_OBJECT_0+Count) then begin Application.ProcessMessages; Continue; end; for i := Integer(Ret-WAIT_OBJECT_0)+1 to High(H) do begin H[i-1] := H[i]; end; Dec(Count); until Count = 0; for i := Low(OpResult) to High(OpResult) do begin Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i],True)); end; finally for i := Low(Threads) to High(Threads) do begin Threads[i].Free; end; end; // Do next jobs with query ... end; 仅限于一次等待最多63(MsgWaitForMultipleObjects() [64]-1)个句柄。 WaitForMultipleObjects()文档说明了如何解决该限制(如果需要)

要等待超过MAXIMUM_WAIT_OBJECTS个句柄,请使用以下方法之一:

  • 创建一个线程以等待MAXIMUM_WAIT_OBJECTS句柄,然后等待该线程以及其他句柄。使用此技术将句柄分成MAXIMUM_WAIT_OBJECTS组。
  • 调用RegisterWaitForSingleObject以等待每个句柄。线程池中的等待线程等待MAXIMUM_WAIT_OBJECTS注册的对象,并在该对象发出信号或超时间隔到期后分配工作线程。

或者,您可以简单地批量处理列表,一次说不超过50至60个项目。