Revised by
Stefan Glienke
ba7623e
| program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Threading;
type
ILock = interface
['{F499E73B-6F7C-4740-9550-F34ED5655272}']
procedure Enter;
procedure Leave;
end;
TInterfacedMonitor = class(TInterfacedObject, ILock)
private
fInstance: TObject;
public
constructor Create(const instance: TObject);
destructor Destroy; override;
procedure Enter;
procedure Leave;
end;
{ TInterfacedMonitor }
constructor TInterfacedMonitor.Create(const instance: TObject);
begin
inherited Create;
fInstance := instance;
Enter;
end;
destructor TInterfacedMonitor.Destroy;
begin
Leave;
inherited;
end;
procedure TInterfacedMonitor.Enter;
begin
MonitorEnter(fInstance);
end;
procedure TInterfacedMonitor.Leave;
begin
MonitorExit(fInstance);
end;
function Lock(const instance: TObject): ILock;
begin
Result := TInterfacedMonitor.Create(instance);
end;
var
o: TObject;
i: Integer;
begin
o := TObject.Create;
i := 0;
TParallel.&For(1, 1000,
procedure(x: Integer)
begin
Lock(o);
Inc(i);
Sleep(1);
Dec(i);
Assert(i = 0);
end);
o.Free;
end.
|