为什么WaitForMultipleObjects会因多个线程句柄而失败?

时间:2016-09-07 22:49:51

标签: multithreading delphi delphi-xe2

在以下测试程序中,每个测试线程在开始执行时将其句柄添加到全局TThreadList,并在其执行即将结束时从同一列表中删除其句柄。

出于测试目的,另外,每个线程确保在主线程锁定列表之前添加其句柄(复制其句柄并开始等待它们完成)。线程还确保在主线程锁定列表之前不会删除它们的句柄。

测试程序运行良好,最多可达50-60个线程。之后,WaitForMultipleObjects调用开始失败,WAIT_FAILEDGetLastError返回87(ERROR_INVALID_PARAMETER)。目前它启动了100个线程。我的问题是,我做错了什么?

该程序使用XE2编译 - 更新4,32位目标平台。测试盒是W7x64。

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  windows,
  sysutils,
  classes,
  syncobjs;

type
  TTestThread = class(TThread)
  private
    FAckStarted: TEvent;
    function GetAckHandle: THandle;
    class var
      ThreadList: TThreadList;
      WaitEnd: THandle;
  protected
    procedure Execute; override;
  public
    constructor Create;
    destructor Destroy; override;
    property AckHandle: THandle read GetAckHandle;
  end;

{.$DEFINE FREEONTERMINATE}

constructor TTestThread.Create;
begin
  inherited Create(True);
  FAckStarted := TEvent.Create;
{$IFDEF FREEONTERMINATE}
  FreeOnTerminate := True;
{$ENDIF}
end;

destructor TTestThread.Destroy;
begin
  FAckStarted.Free;
  inherited;
end;

procedure TTestThread.Execute;
begin
//  OutputDebugString(PChar(Format('%d starting -------------', [Handle])));
  ThreadList.Add(Pointer(Handle));
  FAckStarted.SetEvent;

  NameThreadForDebugging(AnsiString(IntToStr(Handle)));

  WaitForSingleObject(WaitEnd, INFINITE);
  ThreadList.Remove(Pointer(Handle));
//  OutputDebugString(PChar(Format('%d leaving -------------', [Handle])));
end;

function TTestThread.GetAckHandle: THandle;
begin
  Result := FAckStarted.Handle;
end;

const
  NumThreads = 100;

var
  DeferThreadEnd: TEvent;
  ThreadList: array of TThread;
  i: Integer;
  Thread: TTestThread;
  WaitThreadStart: THandle;
  LockList: TList;
  LockListCount: Integer;
  ThreadHandleArr: array of THandle;
  WaitRet: DWORD;
begin
  IsMultiThread := True;
  ReportMemoryLeaksOnShutdown := True;

  TTestThread.ThreadList := TThreadList.Create;
  DeferThreadEnd := TEvent.Create;
  TTestThread.WaitEnd := DeferThreadEnd.Handle;

  SetLength(ThreadList, NumThreads);
  for i := 0 to NumThreads - 1 do begin
    Thread := TTestThread.Create;
    ThreadList[i] := Thread;
    WaitThreadStart := Thread.GetAckHandle;
    Thread.Start;
    WaitForSingleObject(WaitThreadStart, INFINITE);
  end;

  LockList := TTestThread.ThreadList.LockList;
  LockListCount := LockList.Count;
  SetLength(ThreadHandleArr, LockListCount);
  for i := 0 to LockListCount - 1 do
{$IFDEF FREEONTERMINATE}
    Win32Check(DuplicateHandle(GetCurrentProcess, THandle(LockList[i]),
            GetCurrentProcess, @ThreadHandleArr[i], SYNCHRONIZE, True, 0));
{$ELSE}
    ThreadHandleArr[i] := THandle(LockList[i]);
{$ENDIF}
  TTestThread.ThreadList.UnlockList;

  DeferThreadEnd.SetEvent;
  if LockListCount > 0 then begin
    Writeln('waiting for ', LockListCount, ' threads');
    WaitRet := WaitForMultipleObjects(LockListCount,
                              PWOHandleArray(ThreadHandleArr), True, INFINITE);
    case WaitRet of
      WAIT_OBJECT_0: Writeln('wait success');
      WAIT_FAILED: Writeln('wait fail:', SysErrorMessage(GetLastError));
    end;
  end;

  for i := 0 to Length(ThreadList) - 1 do begin
{$IFDEF FREEONTERMINATE}
    Win32Check(CloseHandle(ThreadHandleArr[i]));
{$ELSE}
    ThreadList[i].Free;
{$ENDIF}
  end;
  DeferThreadEnd.Free;
  TTestThread.ThreadList.Free;
  Writeln('program end');
  Readln;
end.

1 个答案:

答案 0 :(得分:21)

<button ng-click="getVar(radioResult)"... documentation州:

  

最大对象句柄数为MAXIMUM_WAIT_OBJECTS。

WaitForMultipleObjects()的值为64(在MAXIMUM_WAIT_OBJECTS中定义),因此100个句柄超出限制。但是,文档还解释了如何克服该限制:

  

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

     
      
  • 创建一个线程以等待MAXIMUM_WAIT_OBJECTS句柄,然后等待该线程加上其他句柄。使用此技术将句柄分成MAXIMUM_WAIT_OBJECTS组。

  •   
  • 调用RegisterWaitForSingleObject在每个句柄上等待。来自线程池的等待线程在MAXIMUM_WAIT_OBJECTS注册的对象上等待,并在发出对象信号或超时间隔到期后分配工作线程。

  •   

请参阅this question的答案,了解第一项技术的示例。