如何从新的线程库中使用TTask.WaitForAny?

时间:2015-03-12 14:27:11

标签: multithreading delphi delphi-xe7 rtl-ppl

尝试使用Delphi中的线程库并行计算任务并使用TTask.WaitForAny()获取第一个计算结果时,异常会暂停执行。

在例外情况下调用堆栈:

  

$ 752D2F71的首次机会异常。异常类EMonitorLockException,消息'对象锁不属于'。处理Project1.exe(11248)

:752d2f71 KERNELBASE.RaiseException + 0x48
System.TMonitor.CheckOwningThread
System.ErrorAt(25,$408C70)
System.Error(reMonitorNotLocked)
System.TMonitor.CheckOwningThread
System.TMonitor.Exit
System.TMonitor.Exit($2180E40)
System.Threading.TTask.RemoveCompleteEvent(???)
System.Threading.TTask.DoWaitForAny((...),4294967295)
System.Threading.TTask.WaitForAny((...))
Project9.Parallel2
Project9.Project1
:74ff919f KERNEL32.BaseThreadInitThunk + 0xe
:7723b54f ntdll.RtlInitializeExceptionChain + 0x8f
:7723b51a ntdll.RtlInitializeExceptionChain + 0x5a

调用堆栈得出的结论是异常是由线程库TMonitor和/或TTask.WaitForAny()中的错误引起的。为了验证这一点,代码被减少到最低限度:

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.Threading, System.Classes, System.SyncObjs,
  System.StrUtils;
var
  WorkerCount : integer = 1000;

function MyTaskProc: TProc;
begin
  result := procedure
    begin
      // Do something
    end;
end;

procedure Parallel2;
var
  i : Integer;
  Ticks: Cardinal;
  tasks: array of ITask;
  LTask: ITask;
  workProc: TProc;
begin
  workProc := MyTaskProc();
  Ticks := TThread.GetTickCount;
  SetLength(tasks, WorkerCount); // number of parallel tasks to undertake
  for i := 0 to WorkerCount - 1 do // parallel tasks
    tasks[i] := TTask.Run(workProc);
  TTask.WaitForAny(tasks); // wait for the first one to finish
  for LTask in tasks do
    LTask.Cancel; // kill the remaining tasks
  Ticks := TThread.GetTickCount - Ticks;
  WriteLn('Parallel time ' + Ticks.ToString + ' ms');
end;

begin
  try
    repeat
      Parallel2;
      WriteLn('finished');
    until FALSE;
  except
    on E: Exception do
      writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

现在错误会在一段时间后重现,并且验证了RTL错误。

这是以RSP-10197 TTask.WaitForAny gives exception EMonitorLockException "Object lock not owned"身份提交给Embarcadero的。


鉴于Delphi线程库目前无法解决这个问题,问题是:

是否有解决方法并行执行程序以获得第一个获得的解决方案?

1 个答案:

答案 0 :(得分:3)

以下是使用TParallel.For在生成答案时停止执行的示例。它使用TParallel.LoopState来指示并行for循环的其他成员。通过使用.Stop信号,应停止所有当前和挂起的迭代。当前迭代应检查loopState.Stopped

procedure Parallel3(CS: TCriticalSection);
var
  Ticks: Cardinal;
  i,ix: Integer;  // variables that are only touched once in the Parallel.For loop
begin
  i := 0;
  Ticks := TThread.GetTickCount;
  TParallel.For(1,WorkerCount,
    procedure(index:Integer; loopState: TParallel.TLoopState)
    var
      k,l,m: Integer;
    begin
      // Do something complex
      k := (1000 - index)*1000;
      for l := 0 to Pred(k) do
        m := k div 1000;
      // If criteria to stop fulfilled:
      CS.Enter;
      Try
        if loopState.Stopped then // A solution was already found
          Exit;
        loopState.Stop;  // Signal 
        Inc(i);
        ix := index;
      Finally
        CS.Leave;
      End;
    end
  );
  Ticks := TThread.GetTickCount - Ticks;
  WriteLn('Parallel time ' + Ticks.ToString + ' ticks', ' i :',i,' index:',ix);
end;

关键部分保护计算结果,这里为了简单起见i,ix。


免责声明,鉴于System.Threading库中的错误状态,我建议使用OTL框架的另一种解决方案。至少在图书馆达到稳定的基础之前。