-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFutureValue.pas
94 lines (73 loc) · 2.21 KB
/
FutureValue.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// Copyright (c) Jasper Schellingerhout. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
// I kindly request that you notify me if you use this in your software projects.
// Project located at: https://github.com/schellingerhout/active-object-delphi
unit FutureValue;
interface
uses
system.syncobjs;
type
IFutureValue<T> = interface(IInterface)
function GetValue: T;
property Value: T read GetValue;
end;
TFutureValue<T> = class(TInterfacedObject, IFutureValue<T>)
private
FResultSet: boolean;
FResult: T;
FValueReadyEvent: TLightWeightEvent;
// consider balance between TEvent and TLightweight event
function GetValue: T;
function Wait: boolean;
function GetValueReadyEvent: TLightWeightEvent;
protected
property ValueReadyEvent: TLightWeightEvent read GetValueReadyEvent;
public
destructor Destroy; override;
procedure SetValue(AResult: T); // done by methodrequest wrapping a future
property Value: T read GetValue;
end;
implementation
{ TActiveFuture<T> }
destructor TFutureValue<T>.Destroy;
begin
FValueReadyEvent.Free;
inherited;
end;
function TFutureValue<T>.GetValue: T;
begin
Wait;
result := FResult;
end;
function TFutureValue<T>.GetValueReadyEvent: TLightWeightEvent;
var
LEvent: TLightWeightEvent;
begin
if FValueReadyEvent = nil then
begin
LEvent := TLightWeightEvent.Create;
if TInterlocked.CompareExchange<TLightWeightEvent>(FValueReadyEvent, LEvent,
nil) <> nil then
LEvent.Free;
if FResultSet then
FValueReadyEvent.SetEvent;
end;
result := FValueReadyEvent;
end;
procedure TFutureValue<T>.SetValue(AResult: T);
begin
//raise exception if set twice!
FResult := AResult; //no -one can read until we set the flag anyway.
FResultSet := true; //don't think interlock exchange is needed
GetValueReadyEvent.SetEvent;
end;
function TFutureValue<T>.Wait: boolean;
begin
if FResultSet then //set after value is set
result := true
else
result := ValueReadyEvent.WaitFor(INFINITE) <> TWaitResult.wrTimeout;
end;
end.