The Parallel Programming Library

PPL features: TTask, ITask, IFuture<T>, TParallel.For, TParallel.Join, TThreadPool, task status, exception aggregation (EAggregateException).

Third-party: OmniThreadLibrary (powerful pipelines, blocking collections, async/await-like constructs; Windows), Spring4D tasks.

uses System.Threading;

// TTask: run work on the thread pool
var T := TTask.Run(
  procedure
  begin
    Sleep(1000);
    TThread.Queue(nil, procedure begin Label1.Caption := 'Done'; end);
  end);

// IFuture<T>: a task returning a value
var F := TTask.Future<Integer>(
  function: Integer
  begin
    Result := ComputeExpensiveValue;
  end);
Writeln(F.Value);                  // blocks until the result is ready

// Waiting
var Tasks: TArray<ITask> := [TTask.Run(Job1), TTask.Run(Job2), TTask.Run(Job3)];
TTask.WaitForAll(Tasks);
var FirstIdx := TTask.WaitForAny(Tasks);

// Parallel for
TParallel.For(0, High(Images),
  procedure(I: Integer)
  begin
    ProcessImage(Images[I]);
  end);

// Parallel for with a stride and pool control
var Pool := TThreadPool.Create;
Pool.SetMaxWorkerThreads(4);
TParallel.For(1, 0, 999, procedure(I: Int64) begin Work(I); end, Pool);

// Cancellation
var Task := TTask.Create(procedure begin
  while True do
  begin
    TTask.CurrentTask.CheckCanceled;    // raises EOperationCancelled if cancelled
    DoStep;
  end;
end);
Task.Start;
Task.Cancel;