TLightweightEvent (Object Pascal)

From Appmethod Code Examples
Jump to: navigation, search

Description

This example illustrates the use of the TLightweightEvent class.

The main thread does the following: creates a secondary thread, waits 100 milliseconds, and then sets the application-specific event ReadyFlag. The secondary thread cannot perform a certain operation (display a message) until ReadyFlag is set, so it is blocked for approximately 100 milliseconds.

Code

program TLightweightEvent_example;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, SyncObjs;

var
  ReadyFlag: TLightweightEvent;

type
  TThreadRoadRunner = class(TThread)
  private
    FReadyFlag: TSynchroObject;
    procedure Execute; override;
  public
    constructor Create(ASyncObj: TSynchroObject);
  end;

procedure TThreadRoadRunner.Execute;
begin
  FReadyFlag.Acquire; { Polymorphic call }
  Writeln('Running started');
end;

constructor TThreadRoadRunner.Create(ASyncObj: TSynchroObject);
begin
  inherited Create(True);
  FReadyFlag := ASyncObj;
end;

var
  RoadRunner: TThreadRoadRunner;

begin
  ReadyFlag := TLightweightEvent.Create;

  RoadRunner := TThreadRoadRunner.Create(ReadyFlag);
  RoadRunner.Start;

  Sleep(100);
  ReadyFlag.SetEvent;
  Sleep(100);

end. { Put breakpoint here to see the console output. }

Uses