How can I use TTask.WaitForAny from the new threading library?

前端 未结 1 1641
鱼传尺愫
鱼传尺愫 2021-01-05 09:34

In an attempt to use the threading library in Delphi to calculate tasks in parallel and using TTask.WaitForAny() to get the first calculated result, an exceptio

相关标签:
1条回答
  • 2021-01-05 10:11

    Here is an example using TParallel.For to stop the execution when an answer is produced. It uses the TParallel.LoopState to signal other members of the parallel for loop. By using the .Stop signal, all current and pending iterations should stop. Current iterations should check 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;
    

    The critical section protects the calculated results, here for simplicity i,ix.


    Disclaimer, given the state of bugs galore within the System.Threading library, I would recommend another solution using the OTL framework. At least until the library has reached a stable foundation.

    0 讨论(0)
提交回复
热议问题