SleepSort (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example implements Sleep sort, an esoteric time-based sorting algorithm. The example demonstrates how to use a TCriticalSection object to synchronize output to console.

Code

program SleepSortDemo;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils, Classes, SyncObjs;

type
  TSleepThread = class(TThread)
  private
    FValue: Integer;
    FLock: TCriticalSection;
  protected
    constructor Create(AValue: Integer; ALock: TCriticalSection);
    procedure Execute; override;
  end;

constructor TSleepThread.Create(AValue: Integer; ALock: TCriticalSection);
begin
  FValue := AValue;
  FLock := ALock;
  inherited Create(False);
end;

procedure TSleepThread.Execute;
begin
  Sleep(1000 * FValue);
  FLock.Acquire;
  Write(FValue:3);
  FLock.Release;
end;

const
  ArrLen = 16;

var
  A: array [0 .. ArrLen - 1] of Integer;
  Handles: array [0 .. ArrLen - 1] of THandle;
  Threads: array [0 .. ArrLen - 1] of TThread;
  Lock: TCriticalSection;
  I: Integer;

begin
  // Generate random data
  for I := 0 to ArrLen - 1 do
  begin
    A[I] := Random(ArrLen - 1);
    Write(A[I]:3);
  end;
  Writeln;

  // Create critical section and threads
  Lock := TCriticalSection.Create;
  for I := 0 to ArrLen - 1 do
  begin
    Threads[I] := TSleepThread.Create(A[I], Lock);
    Handles[I] := Threads[I].Handle;
  end;

  // Wait until threads terminate
  // This may take up to ArrLen - 1 seconds
  WaitForMultipleObjects(ArrLen, @Handles, True, INFINITE);

  // Destroy thread instances
  for I := 0 to ArrLen - 1 do
    Threads[I].Free;
  Lock.Free;

  Writeln;
  Readln;

end.

Uses