Einzelnen Beitrag anzeigen

Schokohase
(Gast)

n/a Beiträge
 
#8

AW: TParallels For-Schleife abbrechen

  Alt 21. Apr 2018, 12:33
Lass mal diesen Code laufen:
Delphi-Quellcode:
program ParallelForBreak;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.Diagnostics,
  System.SysUtils,
  System.SyncObjs,
  System.Threading;

var
  s: string;
  sw: TStopwatch;
  ccount, wcount: Integer;
  r: TParallel.TLoopResult;

begin
  try
    ccount := 0;
    wcount := 0;

    sw := TStopwatch.StartNew( );

    r := TParallel.for( 1, 5000,
      procedure( idx: Integer; loopstate: TParallel.TLoopState )
      begin
        TInterlocked.Increment( ccount );

        if loopstate.ShouldExit then
          Exit;

        // Workload
        TInterlocked.Increment( wcount );
        Sleep( 1 );

        // Abbruchbedingung
        if idx = 3800 then
        begin
          loopstate.Break;
        end;
      end );

    sw.Stop( );

    WriteLn( 'LoopResult:' );
    WriteLn( ' Completed: ', r.Completed );
    Writeln( ' LowestBreakIteration: ', r.LowestBreakIteration );

    WriteLn( 'Statistics:' );
    WriteLn( ' IteratorEvent called: ', ccount );
    WriteLn( ' IteratorEvent processed: ', wcount );
    WriteLn( ' Execution time: : ', sw.ElapsedMilliseconds, ' ms' );

    ReadLn( s );
  except
    on E: Exception do
      Writeln( E.ClassName, ': ', E.Message );
  end;
end.
Das Ergebnis hier:
Code:
LoopResult:
  Completed: FALSE
  LowestBreakIteration: 3800
Statistics:
  IteratorEvent called: 3984
  IteratorEvent processed: 3820
  Execution time: : 12799 ms
Soll bedeuten:
- Der IteratorEvent wurde 3984 mal aufgerufen
- Im IteratorEvent wurden 3820 Berechnungen ausgeführt
- Im IteratorEvent wurden somit 164 Berechnungen nicht ausgeführt (vorzeitig abgebrochen)
  Mit Zitat antworten Zitat