├── Extensions
├── Packages
│ └── Integrates
│ │ └── Pool
│ │ ├── ThreadPoolExecutor.bdsproj
│ │ ├── ThreadPoolExecutor.bdsproj.local
│ │ ├── ThreadPoolExecutor.dpk
│ │ └── ThreadPoolExecutor.res
└── Source
│ └── Integrates
│ └── Pool
│ ├── AbstractExecutorService.pas
│ ├── BlockingQueue.pas
│ ├── Callable.pas
│ ├── Collections.pas
│ ├── CompletitionService.pas
│ ├── Exceptions.pas
│ ├── Executor.pas
│ ├── ExecutorCompletitionService.pas
│ ├── ExecutorService.pas
│ ├── Executors.pas
│ ├── Future.pas
│ ├── FutureTask.pas
│ ├── Runnable.pas
│ ├── RunnableFuture.pas
│ ├── ThreadPoolExecutor.pas
│ └── Threading.pas
├── LICENSE
└── README.md
/Extensions/Packages/Integrates/Pool/ThreadPoolExecutor.bdsproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | ThreadPoolExecutor.dpk
14 |
15 |
16 | 7.0
17 |
18 |
19 | 8
20 | 0
21 | 1
22 | 1
23 | 0
24 | 0
25 | 1
26 | 1
27 | 1
28 | 0
29 | 0
30 | 1
31 | 0
32 | 1
33 | 0
34 | 1
35 | 0
36 | 0
37 | 0
38 | 0
39 | 0
40 | 1
41 | 1
42 | 1
43 | 1
44 | 1
45 | True
46 | True
47 | WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;
48 |
49 | False
50 |
51 | True
52 | True
53 | True
54 | True
55 | True
56 | True
57 | True
58 | True
59 | True
60 | True
61 | True
62 | True
63 | True
64 | True
65 | True
66 | True
67 | True
68 | True
69 | True
70 | True
71 | True
72 | True
73 | True
74 | True
75 | True
76 | True
77 | True
78 | True
79 | True
80 | True
81 | True
82 | True
83 | True
84 | True
85 | True
86 | True
87 | True
88 | True
89 | True
90 | True
91 | True
92 | True
93 | True
94 | True
95 | True
96 | True
97 | False
98 | False
99 | False
100 | True
101 | True
102 | True
103 | True
104 | True
105 | True
106 |
107 |
108 |
109 | 0
110 | 0
111 | False
112 | 1
113 | False
114 | False
115 | False
116 | 16384
117 | 1048576
118 | 4194304
119 | Thread Pool - Like JAVA Thread Pool Executor
120 |
121 |
122 |
123 | ..\..\..\Lib
124 |
125 | ..\..\..\Lib
126 |
127 |
128 |
129 |
130 | False
131 |
132 |
133 |
134 |
135 |
136 | False
137 |
138 |
139 | True
140 | False
141 |
142 |
143 |
144 | $00000000
145 |
146 |
147 |
148 | True
149 | False
150 | 1
151 | 0
152 | 0
153 | 0
154 | False
155 | False
156 | False
157 | False
158 | False
159 | 1046
160 | 1252
161 |
162 |
163 |
164 |
165 | 1.0.0.0
166 |
167 |
168 |
169 |
170 |
171 | 1.0.0.0
172 |
173 |
174 | Microsoft Office XP Sample Automation Server Wrapper Components
175 |
176 |
177 |
178 |
--------------------------------------------------------------------------------
/Extensions/Packages/Integrates/Pool/ThreadPoolExecutor.bdsproj.local:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/Extensions/Packages/Integrates/Pool/ThreadPoolExecutor.dpk:
--------------------------------------------------------------------------------
1 | package ThreadPoolExecutor;
2 |
3 | {$R *.res}
4 | {$ALIGN 8}
5 | {$ASSERTIONS ON}
6 | {$BOOLEVAL OFF}
7 | {$DEBUGINFO ON}
8 | {$EXTENDEDSYNTAX ON}
9 | {$IMPORTEDDATA ON}
10 | {$IOCHECKS ON}
11 | {$LOCALSYMBOLS ON}
12 | {$LONGSTRINGS ON}
13 | {$OPENSTRINGS ON}
14 | {$OPTIMIZATION OFF}
15 | {$OVERFLOWCHECKS OFF}
16 | {$RANGECHECKS OFF}
17 | {$REFERENCEINFO ON}
18 | {$SAFEDIVIDE OFF}
19 | {$STACKFRAMES ON}
20 | {$TYPEDADDRESS OFF}
21 | {$VARSTRINGCHECKS ON}
22 | {$WRITEABLECONST OFF}
23 | {$MINENUMSIZE 1}
24 | {$IMAGEBASE $400000}
25 | {$DESCRIPTION 'Thread Pool - Like JAVA Thread Pool Executor'}
26 | {$RUNONLY}
27 | {$IMPLICITBUILD OFF}
28 |
29 | requires
30 | rtl;
31 |
32 | contains
33 | BlockingQueue in '..\..\..\Source\Integrates\Pool\BlockingQueue.pas',
34 | Collections in '..\..\..\Source\Integrates\Pool\Collections.pas',
35 | Exceptions in '..\..\..\Source\Integrates\Pool\Exceptions.pas',
36 | ExecutorService in '..\..\..\Source\Integrates\Pool\ExecutorService.pas',
37 | Threading in '..\..\..\Source\Integrates\Pool\Threading.pas',
38 | ThreadPoolExecutor in '..\..\..\Source\Integrates\Pool\ThreadPoolExecutor.pas',
39 | Future in '..\..\..\Source\Integrates\Pool\Future.pas',
40 | Callable in '..\..\..\Source\Integrates\Pool\Callable.pas',
41 | AbstractExecutorService in '..\..\..\Source\Integrates\Pool\AbstractExecutorService.pas',
42 | RunnableFuture in '..\..\..\Source\Integrates\Pool\RunnableFuture.pas',
43 | FutureTask in '..\..\..\Source\Integrates\Pool\FutureTask.pas',
44 | CompletitionService in '..\..\..\Source\Integrates\Pool\CompletitionService.pas',
45 | ExecutorCompletitionService in '..\..\..\Source\Integrates\Pool\ExecutorCompletitionService.pas',
46 | Executors in '..\..\..\Source\Integrates\Pool\Executors.pas',
47 | Executor in '..\..\..\Source\Integrates\Pool\Executor.pas',
48 | Runnable in '..\..\..\Source\Integrates\Pool\Runnable.pas';
49 |
50 | end.
51 |
--------------------------------------------------------------------------------
/Extensions/Packages/Integrates/Pool/ThreadPoolExecutor.res:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lmbelo/ThreadPoolExecutor4Delphi/327ff9be7f868df3a7c7a2558169d4c474c8ecba/Extensions/Packages/Integrates/Pool/ThreadPoolExecutor.res
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/AbstractExecutorService.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit AbstractExecutorService;
12 |
13 | interface
14 |
15 | uses
16 | ExecutorService, Callable, Future, RunnableFuture, Executor, DateUtils,
17 | Runnable;
18 |
19 | type
20 | TAbstractExecutorService = class abstract(TInterfacedObject, IExecutor, IExecutorService)
21 | protected
22 | procedure DoInvokeAny(const ATasks: TCallableList; const ATimed: boolean; ATimeOut: Int64; out AResult: pointer);
23 | public
24 | function NewTaskFor(const ATask: IRunnable; var AResult: pointer): ITaskFuture; overload;
25 | function NewTaskFor(const ACallable: ICallable): ITaskFuture; overload;
26 | public
27 | //IExecutor implementation
28 | function GetAsObject(): TObject;
29 | procedure Execute(const ACommand: IRunnable); virtual; abstract;
30 |
31 | //IExecutorService implementation
32 | procedure Shutdown; virtual; abstract;
33 | function ShutdownNow: TRunnableArray; virtual; abstract;
34 | function IsShutdown: boolean; virtual; abstract;
35 | function IsTerminated: boolean; virtual; abstract;
36 | function AwaitTermination(const ATimeOut: int64): boolean; virtual; abstract;
37 |
38 | function Submit(const ATask: ICallable): IFuture; overload;
39 | function Submit(const ATask: IRunnable; var AResult: pointer): IFuture; overload;
40 | function Submit(const ATask: IRunnable): IFuture; overload;
41 | function InvokeAll(const ATasks: TCallableList): TFutureList; overload;
42 | function InvokeAll(const ATasks: TCallableList; ATimeOut: Int64): TFutureList; overload;
43 | procedure InvokeAny(const ATasks: TCallableList; out AResult: pointer); overload;
44 | procedure InvokeAny(const ATasks: TCallableList; ATimeOut: Int64; out AResult: pointer); overload;
45 | end;
46 |
47 | implementation
48 |
49 | uses
50 | FutureTask, SysUtils, Exceptions, ExecutorCompletitionService, Classes;
51 |
52 | { TAbstractExecutorService }
53 |
54 | procedure TAbstractExecutorService.DoInvokeAny(const ATasks: TCallableList;
55 | const ATimed: boolean; ATimeOut: Int64; out AResult: pointer);
56 | var
57 | LNTasks: integer;
58 | LFutures: TFutureList;
59 | LEcs: TExecutorCompletitionService;
60 | LEE: EExecution;
61 | LActive: integer;
62 | LFuture: IFuture;
63 | LEnumerator: TInterfaceListEnumerator;
64 | LNow: TDateTime;
65 | LLastTime: TDateTime;
66 | I: Integer;
67 | begin
68 | if not Assigned(ATasks) then raise ENullPointer.Create();
69 | LNTasks := ATasks.Count;
70 | if (LNTasks = 0) then raise EIllegalArgument.Create();
71 |
72 | LFutures := TFutureList.Create();
73 | try
74 | LEcs := TExecutorCompletitionService.Create(Self);
75 | try
76 | try
77 | LEE := nil;
78 | if ATimed then LLastTime := Now() else LLastTime := MinDateTime;
79 | LEnumerator := ATasks.GetEnumerator();
80 | LEnumerator.MoveNext;
81 | LFutures.Add(LEcs.Submit(ICallable(LEnumerator.Current)));
82 | Dec(LNTasks);
83 | LActive := 1;
84 | while true do begin
85 | LFuture := LEcs.Poll();
86 | if not Assigned(LFuture) then begin
87 | if (LNTasks > 0) then begin
88 | Dec(LNTasks);
89 | LEnumerator.MoveNext;
90 | LFutures.Add(LEcs.Submit(ICallable(LEnumerator.Current)));
91 | Inc(LActive);
92 | end else if (LActive = 0) then begin
93 | Break;
94 | end else if (ATimed) then begin
95 | LFuture := LEcs.Poll(ATimeOut);
96 | if not Assigned(LFuture) then raise ETimeout.Create();
97 | LNow := Now();
98 | IncMilliSecond(ATimeOut, - MilliSecondsBetween(LLastTime, LNow));
99 | LLastTime := LNow;
100 | end else begin
101 | LFuture := LEcs.Take();
102 | end;
103 | end else begin
104 | Dec(LActive);
105 | try
106 | LFuture.GetResult(AResult);
107 | Exit;
108 | except
109 | on E: EExecution do begin
110 | LEE := EExecution.Create(E.Message);
111 | end;
112 | end;
113 | end;
114 | end;
115 |
116 | if not Assigned(LEE) then LEE := EExecution.Create('Execution failed.');
117 |
118 | raise LEE;
119 | finally
120 | for I := 0 to LFutures.Count - 1 do begin
121 | IFuture(LFutures[I]).Cancel(true);
122 | end;
123 | end;
124 | finally
125 | LEcs.Free;
126 | end;
127 | finally
128 | LFutures.Free;
129 | end;
130 | end;
131 |
132 | function TAbstractExecutorService.GetAsObject: TObject;
133 | begin
134 | Result := Self;
135 | end;
136 |
137 | function TAbstractExecutorService.InvokeAll(const ATasks: TCallableList;
138 | ATimeOut: Int64): TFutureList;
139 | var
140 | LFutures: TFutureList;
141 | LDone: boolean;
142 | I: Integer;
143 | J: integer;
144 | LLastTime: TDateTime;
145 | LEnumerator: TInterfaceListEnumerator;
146 | LNow: TDateTime;
147 | LNil: pointer;
148 | begin
149 | if not Assigned(ATasks) then raise ENullPointer.Create();
150 | LFutures := TFutureList.Create();
151 | LDone := false;
152 | try
153 | for I := 0 to ATasks.Count - 1 do begin
154 | LFutures.Add(NewTaskFor(ICallable(ATasks[I])));
155 |
156 | LLastTime := Now();
157 |
158 | LEnumerator := ATasks.GetEnumerator();
159 | while LEnumerator.MoveNext do begin
160 | Execute(IRunnable(LEnumerator.Current));
161 | LNow := Now();
162 | IncMilliSecond(ATimeOut, - MilliSecondsBetween(LLastTime, LNow));
163 | LLastTime := LNow;
164 | if (ATimeOut <= 0) then begin
165 | Result := LFutures;
166 | Exit;
167 | end;
168 | end;
169 |
170 | for J := 0 to LFutures.Count - 1 do begin
171 | if not (IFuture(LFutures[J]).IsDone()) then begin
172 | if (ATimeOut <= 0) then begin
173 | Result := LFutures;
174 | Exit;
175 | end;
176 |
177 | try
178 | LNil := nil;
179 | IFuture(LFutures[J]).GetResult(LNil);
180 | except
181 | on E: ECancellation do begin
182 | end;
183 | on E: EExecution do begin
184 | end;
185 | on E: ETimeOut do begin
186 | Result := LFutures;
187 | Exit;
188 | end;
189 | end;
190 | LNow := Now();
191 | IncMilliSecond(ATimeOut, - MilliSecondsBetween(LLastTime, LNow));
192 | LLastTime := Now();
193 | end;
194 | end;
195 | end;
196 | LDone := true;
197 | Result := LFutures;
198 | finally
199 | if not (LDone) then begin
200 | for I := 0 to LFutures.Count - 1 do begin
201 | IFuture(LFutures[I]).Cancel(true);
202 | end;
203 | end;
204 | end;
205 | end;
206 |
207 | function TAbstractExecutorService.InvokeAll(
208 | const ATasks: TCallableList): TFutureList;
209 | var
210 | LFutures: TFutureList;
211 | LDone: boolean;
212 | I: integer;
213 | LFuture: ITaskFuture;
214 | LNil: pointer;
215 | begin
216 | if not Assigned(ATasks) then raise ENullPointer.Create();
217 | LFutures := TFutureList.Create();
218 | LDone := false;
219 | try
220 | for I := 0 to ATasks.Count - 1 do begin
221 | LFuture := NewTaskFor(ICallable(ATasks[I]));
222 | LFutures.Add(LFuture);
223 | Execute(IRunnable(LFuture));
224 | end;
225 | for I := 0 to LFutures.Count - 1 do begin
226 | if not (IFuture(LFutures[I]).IsDone()) then begin
227 | try
228 | LNil := nil;
229 | IFuture(LFutures[I]).GetResult(LNil);
230 | except
231 | on E: ECancellation do begin
232 | end;
233 | on E: EExecution do begin
234 | end;
235 | end;
236 | end;
237 | end;
238 | LDone := true;
239 | Result := LFutures;
240 | finally
241 | if not (LDone) then begin
242 | for I := 0 to LFutures.Count - 1 do begin
243 | IFuture(LFutures[I]).Cancel(true);
244 | end;
245 | end;
246 | end;
247 | end;
248 |
249 | procedure TAbstractExecutorService.InvokeAny(const ATasks: TCallableList;
250 | ATimeOut: Int64; out AResult: pointer);
251 | begin
252 | DoInvokeAny(ATasks, true, ATimeOut, AResult);
253 | end;
254 |
255 | function TAbstractExecutorService.NewTaskFor(
256 | const ACallable: ICallable): ITaskFuture;
257 | begin
258 | Result := TFutureTask.Create(ACallable);
259 | end;
260 |
261 | function TAbstractExecutorService.NewTaskFor(const ATask: IRunnable;
262 | var AResult: pointer): ITaskFuture;
263 | begin
264 | Result := TFutureTask.Create(ATask, AResult);
265 | end;
266 |
267 | procedure TAbstractExecutorService.InvokeAny(const ATasks: TCallableList;
268 | out AResult: pointer);
269 | begin
270 | try
271 | DoInvokeAny(ATasks, false, 0, AResult);
272 | except
273 | on E: ETimeOut do begin
274 | Assert(false);
275 | end;
276 | end;
277 | end;
278 |
279 | function TAbstractExecutorService.Submit(const ATask: IRunnable): IFuture;
280 | var
281 | LTask: ITaskFuture;
282 | LNil: pointer;
283 | begin
284 | if not Assigned(ATask) then raise ENullPointer.Create();
285 | LNil := nil;
286 | LTask := NewTaskFor(ATask, LNil);
287 | Execute(LTask as IRunnable);
288 | Result := LTask as IFuture;
289 | end;
290 |
291 | function TAbstractExecutorService.Submit(const ATask: IRunnable;
292 | var AResult: pointer): IFuture;
293 | var
294 | LTask: ITaskFuture;
295 | begin
296 | if not Assigned(ATask) then raise ENullPointer.Create();
297 | LTask := NewTaskFor(ATask, AResult);
298 | Execute(LTask as IRunnable);
299 | Result := LTask as IFuture;
300 | end;
301 |
302 | function TAbstractExecutorService.Submit(const ATask: ICallable): IFuture;
303 | var
304 | LTask: ITaskFuture;
305 | begin
306 | if not Assigned(ATask) then raise ENullPointer.Create();
307 | LTask := NewTaskFor(ATask);
308 | Execute(LTask as IRunnable);
309 | Result := LTask as IFuture;
310 | end;
311 |
312 | end.
313 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/BlockingQueue.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit BlockingQueue;
12 |
13 | interface
14 |
15 | uses
16 | SyncObjs, DateUtils, SysUtils, Classes, Collections, Exceptions;
17 |
18 | type
19 | TPointerArray = array of pointer;
20 | TInterfaceArray = array of IInterface;
21 | TBlockingQueue = class(TDataQueue)
22 | private
23 | FLockQueue, FLockItem, FLockSpace: TCriticalSection;
24 | FCapacity: integer;
25 | FInterrupted: boolean;
26 | procedure CheckCapacity;
27 | procedure CheckNull(const AItem: pointer);
28 | procedure CheckEmpty;
29 | procedure WaitForSpace(); overload;
30 | procedure WaitForItem(); overload;
31 | function HasAvailableSpace(): boolean;
32 | function HasAvailableItem(): boolean;
33 | function WaitForSpace(const ATimeOut: Int64): boolean; overload;
34 | function WaitForItem(const ATimeOut: Int64): boolean; overload;
35 | procedure DoSleep(const AMilliSeconds: cardinal);
36 | protected
37 | constructor Create(const ADataType: TDataQueue.TDataType; const ACapacity: integer); reintroduce; overload; virtual;
38 | protected
39 | function Add(const AItem): boolean;
40 | function Remove(const AItem): boolean;
41 | procedure Element(var AItem);
42 |
43 | function Offer(const AItem): boolean; overload;
44 | procedure Poll(var AItem); overload;
45 | procedure Peek(var AItem);
46 |
47 | procedure Put(const AItem);
48 | procedure Take(var AItem);
49 |
50 | function Offer(const AItem; const ATimeOut: Int64): boolean; overload;
51 | procedure Poll(var AItem; const ATimeOut: Int64); overload;
52 | public
53 | constructor Create; reintroduce; overload;
54 | constructor Create(const ACapacity: integer); reintroduce; overload;
55 | destructor Destroy; override;
56 |
57 | function Count: integer;
58 | function IsEmpty: boolean;
59 | function RemainingCapacity: integer;
60 | function ToArray: TPointerArray;
61 |
62 | property Capacity: integer read FCapacity write FCapacity;
63 | end;
64 |
65 | TInterfaceBlockingQueue = class(TBlockingQueue)
66 | protected
67 | constructor Create(const ADataType: TDataQueue.TDataType; const ACapacity: integer); overload; override;
68 | public
69 | function Add(const AItem: IInterface): boolean;
70 | function Remove(const AItem: IInterface): boolean;
71 | function Element(): IInterface;
72 |
73 | function Offer(const AItem: IInterface): boolean; overload;
74 | function Poll: IInterface; overload;
75 | function Peek: IInterface;
76 |
77 | procedure Put(const AItem: IInterface);
78 | function Take: IInterface;
79 |
80 | function Offer(const AItem: IInterface; const ATimeOut: Int64): boolean; overload;
81 | function Poll(const ATimeOut: Int64): IInterface; overload;
82 |
83 | function ToArray: TInterfaceArray;
84 | end;
85 |
86 | TObjectBlockingQueue = class(TBlockingQueue)
87 | protected
88 | constructor Create(const ADataType: TDataQueue.TDataType; const ACapacity: integer); overload; override;
89 | public
90 | function Add(const AItem: TObject): boolean;
91 | function Remove(const AItem: TObject): boolean;
92 | function Element(): TObject;
93 |
94 | function Offer(const AItem: TObject): boolean; overload;
95 | function Poll: TObject; overload;
96 | function Peek: TObject; overload;
97 |
98 | procedure Put(const AItem: TObject);
99 | function Take: TObject;
100 |
101 | function Offer(const AItem: TObject; const ATimeOut: Int64): boolean; overload;
102 | function Poll(const ATimeOut: Int64): TObject; overload;
103 |
104 | function ToArray: TPointerArray;
105 | end;
106 |
107 | implementation
108 |
109 | uses
110 | Windows, TypInfo, Threading;
111 |
112 | { TBlockingQueue }
113 |
114 | constructor TBlockingQueue.Create(const ADataType: TDataQueue.TDataType;
115 | const ACapacity: integer);
116 | begin
117 | inherited Create(ADataType);
118 | FLockQueue := TCriticalSection.Create;
119 | FLockItem := TCriticalSection.Create;
120 | FLockSpace := TCriticalSection.Create;
121 | FCapacity := ACapacity;
122 | FInterrupted := false;
123 | end;
124 |
125 | constructor TBlockingQueue.Create;
126 | begin
127 | Create(System.MaxInt);
128 | end;
129 |
130 | constructor TBlockingQueue.Create(const ACapacity: integer);
131 | begin
132 | Create(dtPointer, ACapacity)
133 | end;
134 |
135 | destructor TBlockingQueue.Destroy;
136 | begin
137 | FInterrupted := true;
138 | FLockSpace.Free;
139 | FLockItem.Free;
140 | FLockQueue.Free;
141 | inherited;
142 | end;
143 |
144 | procedure TBlockingQueue.DoSleep(const AMilliSeconds: cardinal);
145 | var
146 | LCurThread: TCustomThread;
147 | begin
148 | LCurThread := TCustomThread.GetCurrentThread as TCustomThread;
149 | if Assigned(LCurThread) then begin
150 | LCurThread.Sleep(AMilliSeconds);
151 | end else begin
152 | SleepEx(AMilliSeconds, true)
153 | end;
154 | end;
155 |
156 | function TBlockingQueue.Add(const AItem): boolean;
157 | begin
158 | CheckNull(Pointer(AItem));
159 | CheckCapacity;
160 | FLockQueue.Acquire;
161 | try
162 | Push(AItem);
163 | Result := List.IndexOf(Pointer(AItem)) >= 0;
164 | finally
165 | FLockQueue.Release;
166 | end;
167 | end;
168 |
169 | procedure TBlockingQueue.Element(var AItem);
170 | begin
171 | CheckEmpty();
172 | FLockQueue.Acquire();
173 | try
174 | Peek(AItem)
175 | finally
176 | FLockQueue.Release();
177 | end;
178 | end;
179 |
180 | function TBlockingQueue.HasAvailableItem: boolean;
181 | begin
182 | Result := Count > 0;
183 | end;
184 |
185 | function TBlockingQueue.HasAvailableSpace: boolean;
186 | begin
187 | Result := (FCapacity > Count)
188 | end;
189 |
190 | procedure TBlockingQueue.CheckCapacity;
191 | begin
192 | if RemainingCapacity = 0 then raise EIllegalState.Create;
193 | end;
194 |
195 | procedure TBlockingQueue.CheckEmpty;
196 | begin
197 | if IsEmpty then raise ENoSuchElement.Create;
198 | end;
199 |
200 | procedure TBlockingQueue.CheckNull(const AItem: pointer);
201 | begin
202 | if not Assigned(AItem) then raise ENullPointer.Create;
203 | end;
204 |
205 | function TBlockingQueue.Count: Integer;
206 | begin
207 | FLockQueue.Acquire();
208 | try
209 | Result := inherited Count;
210 | finally
211 | FLockQueue.Release();
212 | end;
213 | end;
214 |
215 | function TBlockingQueue.IsEmpty: boolean;
216 | begin
217 | FLockQueue.Acquire();
218 | try
219 | Result := inherited Count = 0;
220 | finally
221 | FLockQueue.Release();
222 | end;
223 | end;
224 |
225 | function TBlockingQueue.Offer(const AItem): boolean;
226 | begin
227 | CheckNull(Pointer(AItem));
228 | FLockQueue.Acquire();
229 | try
230 | Result := ((FCapacity - Count) > 0);
231 | if Result then begin
232 | Push(AItem);
233 | Result := List.IndexOf(Pointer(AItem)) >= 0;
234 | end;
235 | finally
236 | FLockQueue.Release();
237 | end;
238 | end;
239 |
240 | function TBlockingQueue.Offer(const AItem;
241 | const ATimeOut: Int64): boolean;
242 | begin
243 | CheckNull(Pointer(AItem));
244 | Result := false;
245 | FLockSpace.Acquire();
246 | try
247 | if WaitForSpace(ATimeOut) then begin
248 | FLockQueue.Acquire();
249 | try
250 | Push(AItem);
251 | Result := List.IndexOf(Pointer(AItem)) >= 0;
252 | finally
253 | FLockQueue.Release();
254 | end;
255 | end;
256 | finally
257 | FLockSpace.Release();
258 | end;
259 | end;
260 |
261 | procedure TBlockingQueue.Peek(var AItem);
262 | begin
263 | FLockQueue.Acquire();
264 | try
265 | if HasAvailableItem() then begin
266 | Peek(AItem);
267 | end;
268 | finally
269 | FLockQueue.Release();
270 | end;
271 | end;
272 |
273 | procedure TBlockingQueue.Poll(var AItem; const ATimeOut: Int64);
274 | begin
275 | FLockItem.Acquire();
276 | try
277 | if WaitForItem(ATimeOut) then begin
278 | FLockQueue.Acquire();
279 | try
280 | Pop(AItem);
281 | finally
282 | FLockQueue.Release();
283 | end;
284 | end else Pointer(AItem) := nil;
285 | finally
286 | FLockItem.Release();
287 | end;
288 | end;
289 |
290 | procedure TBlockingQueue.Poll(var AItem);
291 | begin
292 | FLockQueue.Acquire();
293 | try
294 | if HasAvailableItem() then begin
295 | Pop(AItem);
296 | end;
297 | finally
298 | FLockQueue.Release();
299 | end;
300 | end;
301 |
302 | procedure TBlockingQueue.Put(const AItem);
303 | begin
304 | CheckNull(Pointer(AItem));
305 | FLockSpace.Acquire();
306 | try
307 | WaitForSpace();
308 | FLockQueue.Acquire();
309 | try
310 | Push(AItem)
311 | finally
312 | FLockQueue.Release();
313 | end;
314 | finally
315 | FLockSpace.Release();
316 | end;
317 | end;
318 |
319 | function TBlockingQueue.RemainingCapacity: integer;
320 | begin
321 | FLockQueue.Acquire();
322 | try
323 | Result := FCapacity - Count;
324 | finally
325 | FLockQueue.Release();
326 | end;
327 | end;
328 |
329 | function TBlockingQueue.Remove(const AItem): boolean;
330 | begin
331 | CheckEmpty();
332 | FLockQueue.Acquire();
333 | try
334 | Result := Remove(AItem);
335 | finally
336 | FLockQueue.Release();
337 | end;
338 | end;
339 |
340 | procedure TBlockingQueue.Take(var AItem);
341 | begin
342 | FLockItem.Acquire();
343 | try
344 | WaitForItem();
345 | FLockQueue.Acquire();
346 | try
347 | Pop(AItem);
348 | finally
349 | FLockQueue.Release();
350 | end;
351 | finally
352 | FLockItem.Release();
353 | end;
354 | end;
355 |
356 | function TBlockingQueue.ToArray: TPointerArray;
357 | var
358 | LList: PPointerList;
359 | I: Integer;
360 | begin
361 | FLockQueue.Acquire;
362 | try
363 | LList := List.List;
364 | SetLength(Result, List.Count);
365 | for I := 0 to List.Count - 1 do begin
366 | Result[I] := LList^[I];
367 | end;
368 | finally
369 | FLockQueue.Release;
370 | end;
371 | end;
372 |
373 | procedure TBlockingQueue.WaitForItem;
374 | begin
375 | while (Count = 0) do begin
376 | DoSleep(500);
377 | end;
378 | end;
379 |
380 | procedure TBlockingQueue.WaitForSpace;
381 | begin
382 | while (FCapacity <= Count) do begin
383 | DoSleep(500);
384 | end;
385 | end;
386 |
387 | function TBlockingQueue.WaitForItem(const ATimeOut: Int64): boolean;
388 | var
389 | LEntryTime: TDateTime;
390 | begin
391 | LEntryTime := Now();
392 | while (Count = 0) and (IncMilliSecond(LEntryTime, ATimeOut) > Now()) do begin
393 | DoSleep(500);
394 | end;
395 | Result := HasAvailableItem();
396 | end;
397 |
398 | function TBlockingQueue.WaitForSpace(const ATimeOut: Int64): boolean;
399 | var
400 | LEntryTime: TDateTime;
401 | begin
402 | LEntryTime := Now();
403 | while not HasAvailableSpace() and (IncMilliSecond(LEntryTime, ATimeOut) > Now()) do begin
404 | DoSleep(500);
405 | end;
406 | Result := (FCapacity > Count);
407 | end;
408 |
409 | { TInterfaceBlockingQueue }
410 |
411 | function TInterfaceBlockingQueue.Add(const AItem: IInterface): boolean;
412 | begin
413 | Result := inherited Add(AItem);
414 | end;
415 |
416 | constructor TInterfaceBlockingQueue.Create(const ADataType: TDataQueue.TDataType;
417 | const ACapacity: integer);
418 | begin
419 | inherited Create(dtInterface, ACapacity);
420 | end;
421 |
422 | function TInterfaceBlockingQueue.Element: IInterface;
423 | begin
424 | Result := nil;
425 | inherited Element(Result);
426 | end;
427 |
428 | function TInterfaceBlockingQueue.Offer(const AItem: IInterface): boolean;
429 | begin
430 | Result := inherited Offer(AItem);
431 | end;
432 |
433 | function TInterfaceBlockingQueue.Offer(const AItem: IInterface;
434 | const ATimeOut: Int64): boolean;
435 | begin
436 | Result := inherited Offer(AItem, ATimeOut);
437 | end;
438 |
439 | function TInterfaceBlockingQueue.Peek: IInterface;
440 | begin
441 | Result := nil;
442 | inherited Peek(Result);
443 | end;
444 |
445 | function TInterfaceBlockingQueue.Poll: IInterface;
446 | begin
447 | Result := nil;
448 | inherited Poll(Result);
449 | end;
450 |
451 | function TInterfaceBlockingQueue.Poll(const ATimeOut: Int64): IInterface;
452 | begin
453 | Result := nil;
454 | inherited Poll(Result, ATimeOut);
455 | end;
456 |
457 | procedure TInterfaceBlockingQueue.Put(const AItem: IInterface);
458 | begin
459 | inherited Put(AItem);
460 | end;
461 |
462 | function TInterfaceBlockingQueue.Remove(const AItem: IInterface): boolean;
463 | begin
464 | Result := inherited Remove(AItem);
465 | end;
466 |
467 | function TInterfaceBlockingQueue.Take: IInterface;
468 | begin
469 | inherited Take(Result);
470 | end;
471 |
472 | function TInterfaceBlockingQueue.ToArray: TInterfaceArray;
473 | var
474 | LList: PPointerList;
475 | I: Integer;
476 | begin
477 | FLockQueue.Acquire;
478 | try
479 | LList := List.List;
480 | SetLength(Result, List.Count);
481 | for I := 0 to List.Count - 1 do begin
482 | Result[I] := IInterface(LList^[I]);
483 | end;
484 | finally
485 | FLockQueue.Release;
486 | end;
487 | end;
488 |
489 | { TObjectBlockingQueue }
490 |
491 | function TObjectBlockingQueue.Add(const AItem: TObject): boolean;
492 | begin
493 | Result := inherited Add(pointer(AItem));
494 | end;
495 |
496 | constructor TObjectBlockingQueue.Create(const ADataType: TDataQueue.TDataType;
497 | const ACapacity: integer);
498 | begin
499 | inherited Create(dtObject, ACapacity);
500 | end;
501 |
502 | function TObjectBlockingQueue.Element: TObject;
503 | begin
504 | inherited Element(pointer(Result));
505 | end;
506 |
507 | function TObjectBlockingQueue.Offer(const AItem: TObject): boolean;
508 | begin
509 | Result := inherited Offer(pointer(AItem));
510 | end;
511 |
512 | function TObjectBlockingQueue.Offer(const AItem: TObject;
513 | const ATimeOut: Int64): boolean;
514 | begin
515 | Result := inherited Offer(pointer(AItem), ATimeOut);
516 | end;
517 |
518 | function TObjectBlockingQueue.Peek: TObject;
519 | begin
520 | inherited Peek(pointer(Result));
521 | end;
522 |
523 | function TObjectBlockingQueue.Poll: TObject;
524 | begin
525 | inherited Poll(pointer(Result));
526 | end;
527 |
528 | function TObjectBlockingQueue.Poll(const ATimeOut: Int64): TObject;
529 | begin
530 | inherited Poll(pointer(Result), ATimeOut);
531 | end;
532 |
533 | procedure TObjectBlockingQueue.Put(const AItem: TObject);
534 | begin
535 | inherited Put(pointer(AItem));
536 | end;
537 |
538 | function TObjectBlockingQueue.Remove(const AItem: TObject): boolean;
539 | begin
540 | Result := inherited Remove(pointer(AItem));
541 | end;
542 |
543 | function TObjectBlockingQueue.Take: TObject;
544 | begin
545 | inherited Take(pointer(Result));
546 | end;
547 |
548 | function TObjectBlockingQueue.ToArray: TPointerArray;
549 | var
550 | LList: PPointerList;
551 | I: Integer;
552 | LIntF: IInterface;
553 | begin
554 | FLockQueue.Acquire;
555 | try
556 | LList := List.List;
557 | for I := Low(LList^) to High(LList^) do begin
558 | if not Assigned((LList^[I])) then Exit;
559 | LIntF := IInterface(LList^[I]);
560 | SetLength(Result, I + 1);
561 | Result[I] := LList^[I];
562 | end;
563 | finally
564 | FLockQueue.Release;
565 | end;
566 | end;
567 |
568 | end.
569 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Callable.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Callable;
12 |
13 | interface
14 |
15 | uses
16 | Classes;
17 |
18 | type
19 | ICallable = interface
20 | ['{5D323039-18B6-464E-B2F0-61ACA47E9DA8}']
21 | procedure Call(out Result: pointer);
22 | end;
23 |
24 | TCallableList = class(TInterfaceList)
25 | end;
26 |
27 | implementation
28 |
29 | end.
30 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Collections.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Collections;
12 |
13 | interface
14 |
15 | uses
16 | Classes, Contnrs;
17 |
18 | type
19 | TCustomQueue = class
20 | private
21 | function GetList: TList; type
22 | TQueueEx = class(Contnrs.TQueue)
23 | private
24 | function GetList: TList;
25 | public
26 | property List: TList read GetList;
27 | end;
28 | private
29 | FSysQueue: TQueueEx;
30 | protected
31 | procedure PushItem(const AItem); virtual;
32 | procedure PopItem(var AItem); virtual;
33 | procedure PeekItem(var AItem); virtual;
34 | function RemoveItem(const AItem): boolean; virtual;
35 | public
36 | constructor Create();
37 | destructor Destroy(); override;
38 |
39 | procedure Push(const AItem);
40 | procedure Pop(var AItem);
41 | procedure Peek(var AItem);
42 | function Remove(const AItem): boolean;
43 |
44 | function Count: Integer;
45 | function AtLeast(ACount: Integer): Boolean;
46 |
47 | property List: TList read GetList;
48 | end;
49 |
50 | TDataQueue = class(TCustomQueue)
51 | public type TDataType = (dtPointer, dtObject, dtInterface);
52 | private
53 | FDataType: TDataType;
54 | protected
55 | procedure PushItem(const AItem); override;
56 | procedure PopItem(var AItem); override;
57 | procedure PeekItem(var AItem); override;
58 | function RemoveItem(const AItem): boolean; override;
59 | public
60 | constructor Create(const ADataType: TDataType); virtual;
61 |
62 | property DataType: TDataType read FDataType;
63 | end;
64 |
65 | implementation
66 |
67 | { TQueue }
68 |
69 | function TCustomQueue.AtLeast(ACount: Integer): Boolean;
70 | begin
71 | Result := FSysQueue.AtLeast(ACount);
72 | end;
73 |
74 | function TCustomQueue.Count: Integer;
75 | begin
76 | Result := FSysQueue.Count;
77 | end;
78 |
79 | constructor TCustomQueue.Create;
80 | begin
81 | FSysQueue := TQueueEx.Create();
82 | end;
83 |
84 | destructor TCustomQueue.Destroy;
85 | begin
86 | FSysQueue.Free();
87 | inherited;
88 | end;
89 |
90 | function TCustomQueue.GetList: TList;
91 | begin
92 | Result := FSysQueue.List;
93 | end;
94 |
95 | procedure TCustomQueue.PeekItem(var AItem);
96 | begin
97 | Pointer(AItem) := FSysQueue.Peek;
98 | end;
99 |
100 | procedure TCustomQueue.PopItem(var AItem);
101 | begin
102 | Pointer(AItem) := FSysQueue.Pop;
103 | end;
104 |
105 | procedure TCustomQueue.PushItem(const AItem);
106 | begin
107 | FSysQueue.PushItem(Pointer(AItem));
108 | end;
109 |
110 | function TCustomQueue.RemoveItem(const AItem): boolean;
111 | begin
112 | Result := FSysQueue.List.Remove(Pointer(AItem)) > -1;
113 | end;
114 |
115 | procedure TCustomQueue.Push(const AItem);
116 | begin
117 | PushItem(AItem);
118 | end;
119 |
120 | procedure TCustomQueue.Peek(var AItem);
121 | begin
122 | PeekItem(AItem);
123 | end;
124 |
125 | procedure TCustomQueue.Pop(var AItem);
126 | begin
127 | PopItem(AItem);
128 | end;
129 |
130 | function TCustomQueue.Remove(const AItem): boolean;
131 | begin
132 | Result := RemoveItem(AItem);
133 | end;
134 |
135 | { TQueue.TQueueEx }
136 |
137 | function TCustomQueue.TQueueEx.GetList: TList;
138 | begin
139 | Result := inherited List;
140 | end;
141 |
142 | { TInterfaceQueue }
143 |
144 | constructor TDataQueue.Create(const ADataType: TDataType);
145 | begin
146 | inherited Create;
147 | FDataType := ADataType;
148 | end;
149 |
150 | procedure TDataQueue.PeekItem(var AItem);
151 | var
152 | LItem: Pointer;
153 | begin
154 | LItem := nil;
155 | inherited PeekItem(LItem);
156 | if Assigned(LItem) then begin
157 | if FDataType = dtInterface then begin
158 | IInterface(AItem) := IInterface(LItem);
159 | end else if FDataType = dtObject then begin
160 | TObject(AItem) := TObject(LItem);
161 | end else if FDataType = dtPointer then begin
162 | Pointer(AItem) := Pointer(LItem);
163 | end;
164 | end;
165 | end;
166 |
167 | procedure TDataQueue.PopItem(var AItem);
168 | var
169 | LItem: pointer;
170 | begin
171 | LItem := nil;
172 | inherited PopItem(LItem);
173 | if Assigned(LItem) then begin
174 | if FDataType = dtInterface then begin
175 | IInterface(AItem) := IInterface(LItem);
176 | IInterface(LItem) := nil;
177 | end else if FDataType = dtObject then begin
178 | TObject(AItem) := TObject(LItem);
179 | end else if FDataType = dtPointer then begin
180 | Pointer(AItem) := Pointer(LItem);
181 | end;
182 | end;
183 | end;
184 |
185 | procedure TDataQueue.PushItem(const AItem);
186 | var
187 | LIx: Integer;
188 | begin
189 | inherited PushItem(AItem);
190 | if FDataType = dtInterface then begin
191 | LIx := FSysQueue.List.IndexOf(Pointer(AItem));
192 | FSysQueue.List.List[LIx] := nil;
193 | IInterface(FSysQueue.List.List[LIx]) := IInterface(AItem);
194 | end;
195 | end;
196 |
197 | function TDataQueue.RemoveItem(const AItem): boolean;
198 | var
199 | LIx: integer;
200 | begin
201 | LIx := FSysQueue.List.IndexOf(Pointer(AItem));
202 | Result := LIx > -1;
203 | if Result then begin
204 | if FDataType = dtInterface then begin
205 | IInterface(FSysQueue.List.List[LIx]) := nil;
206 | end;
207 | FSysQueue.List.Delete(LIx);
208 | end;
209 | end;
210 |
211 | end.
212 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/CompletitionService.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit CompletitionService;
12 |
13 | interface
14 |
15 | uses
16 | Callable, Future, ExecutorService, Runnable;
17 |
18 | type
19 | ICompletitionService = interface
20 | ['{3B176084-CE9F-464A-BB8E-B3314FB43516}']
21 | function Submit(const ACallable: ICallable): IFuture; overload;
22 | function Submit(const ATask: IRunnable; var AResult: pointer): IFuture; overload;
23 | function Take(): IFuture;
24 | function Poll(): IFuture; overload;
25 | function Poll(const ATimeOut: integer): IFuture; overload;
26 | end;
27 |
28 | implementation
29 |
30 | end.
31 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Exceptions.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Exceptions;
12 |
13 | interface
14 |
15 | uses
16 | SysUtils;
17 |
18 | type
19 | EIllegalState = class(Exception)
20 | public
21 | constructor Create();
22 | end;
23 |
24 | ENoSuchElement = class(Exception)
25 | public
26 | constructor Create();
27 | end;
28 |
29 | ENullPointer = class(Exception)
30 | public
31 | constructor Create();
32 | end;
33 |
34 | EInterrupted = class(Exception)
35 | public
36 | constructor Create();
37 | end;
38 |
39 | ERejectecExecution = class(Exception)
40 | public
41 | constructor Create();
42 | end;
43 |
44 | EInvalidParameters = class(Exception)
45 | public
46 | constructor Create();
47 | end;
48 |
49 | ECoreThreadNonZeroKeepAliveTime = class(Exception)
50 | public
51 | constructor Create();
52 | end;
53 |
54 | EIllegalArgument = class(Exception)
55 | public
56 | constructor Create();
57 | end;
58 |
59 | ECancellation = class(Exception)
60 | end;
61 |
62 | EExecution = class(Exception)
63 | end;
64 |
65 | ETimeOut = class(Exception)
66 | public
67 | constructor Create();
68 | end;
69 |
70 | implementation
71 |
72 | { EIllegalState }
73 |
74 | constructor EIllegalState.Create;
75 | begin
76 | inherited Create('Element cannot be added at this time due to capacity restrictions.');
77 | end;
78 |
79 | { ENoSuchElement }
80 |
81 | constructor ENoSuchElement.Create;
82 | begin
83 | inherited Create('Queue is empty.')
84 | end;
85 |
86 | { ENullPointer }
87 |
88 | constructor ENullPointer.Create;
89 | begin
90 | inherited Create('Invalid null element.');
91 | end;
92 |
93 | { EInterrupted }
94 |
95 | constructor EInterrupted.Create;
96 | begin
97 | inherited Create('Execution has been interrupted.');
98 | end;
99 |
100 | { ERejectecExecution }
101 |
102 | constructor ERejectecExecution.Create;
103 | begin
104 | inherited Create('Execution was rejected.');
105 | end;
106 |
107 | { EInvalidParameters }
108 |
109 | constructor EInvalidParameters.Create;
110 | begin
111 | inherited Create('Invalid parameters.');
112 | end;
113 |
114 | { ECoreThreadNonZeroKeepAliveTime }
115 |
116 | constructor ECoreThreadNonZeroKeepAliveTime.Create;
117 | begin
118 | inherited Create('Core threads must have nonzero keep alive times');
119 | end;
120 |
121 | { EIllegalArgument }
122 |
123 | constructor EIllegalArgument.Create;
124 | begin
125 | inherited Create('Illegal argument.');
126 | end;
127 |
128 | { ETimeOut }
129 |
130 | constructor ETimeOut.Create;
131 | begin
132 | inherited Create('Operation timeout.');
133 | end;
134 |
135 | end.
136 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Executor.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Executor;
12 |
13 | interface
14 |
15 | uses
16 | ExecutorService, Runnable;
17 |
18 | type
19 | IExecutor = interface
20 | ['{57A71D13-FDB5-4536-B155-2ED136C9AE00}']
21 | function GetAsObject: TObject;
22 | procedure Execute(const ACommand: IRunnable);
23 | end;
24 |
25 | implementation
26 |
27 | end.
28 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/ExecutorCompletitionService.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit ExecutorCompletitionService;
12 |
13 | interface
14 |
15 | uses
16 | CompletitionService, FutureTask, RunnableFuture, Future, ExecutorService,
17 | AbstractExecutorService, BlockingQueue, Callable, Executor, Runnable;
18 |
19 | type
20 | TExecutorCompletitionService = class(TInterfacedObject, ICompletitionService)
21 | private type
22 | TQueueingFuture = class(TFutureTask)
23 | private
24 | FParent: TExecutorCompletitionService;
25 | FTask: IFuture;
26 | protected
27 | procedure Done(); override;
28 | public
29 | constructor Create(const AParent: TExecutorCompletitionService; const ATask: ITaskFuture);
30 | end;
31 | private
32 | FExecutor: IExecutor;
33 | FAES: TAbstractExecutorService;
34 | FCompletitionQueue: TInterfaceBlockingQueue;
35 | private
36 | function NewTaskFor(const ACallable: ICallable): ITaskFuture; overload;
37 | function NewTaskFor(const ATask: IRunnable; var AResult: pointer): ITaskFuture; overload;
38 | public
39 | constructor Create(const AExecutor: IExecutor);
40 |
41 | function Submit(const ACallable: ICallable): IFuture; overload;
42 | function Submit(const ATask: IRunnable; var AResult: pointer): IFuture; overload;
43 | function Take(): IFuture;
44 | function Poll(): IFuture; overload;
45 | function Poll(const ATimeOut: integer): IFuture; overload;
46 | end;
47 |
48 | implementation
49 |
50 | uses
51 | Exceptions;
52 |
53 | { TExecutorCompletitionService.TQueueingFuture }
54 |
55 | constructor TExecutorCompletitionService.TQueueingFuture.Create(
56 | const AParent: TExecutorCompletitionService; const ATask: ITaskFuture);
57 | var
58 | LNil: pointer;
59 | begin
60 | LNil := nil;
61 | inherited Create(ATask as IRunnable, LNil);
62 | FParent := AParent;
63 | FTask := ATask as IFuture;
64 | end;
65 |
66 | procedure TExecutorCompletitionService.TQueueingFuture.Done;
67 | begin
68 | FParent.FCompletitionQueue.Add(FTask);
69 | end;
70 |
71 | { TExecutorCompletitionService }
72 |
73 | function TExecutorCompletitionService.NewTaskFor(
74 | const ACallable: ICallable): ITaskFuture;
75 | begin
76 | if not Assigned(FAES) then
77 | Result := TFutureTask.Create(ACallable)
78 | else
79 | Result := FAES.NewTaskFor(ACallable);
80 | end;
81 |
82 | constructor TExecutorCompletitionService.Create(const AExecutor: IExecutor);
83 | begin
84 | if not Assigned(AExecutor) then raise ENullPointer.Create();
85 | FExecutor := AExecutor;
86 | if (AExecutor.GetAsObject() is TAbstractExecutorService) then begin
87 | FAES := (AExecutor.GetAsObject() as TAbstractExecutorService)
88 | end else begin
89 | FAES := nil
90 | end;
91 | FCompletitionQueue := TInterfaceBlockingQueue.Create()
92 | end;
93 |
94 | function TExecutorCompletitionService.NewTaskFor(const ATask: IRunnable;
95 | var AResult: pointer): ITaskFuture;
96 | begin
97 | if not Assigned(FAES) then
98 | Result := TFutureTask.Create(ATask, AResult)
99 | else
100 | Result := FAES.NewTaskFor(ATask, AResult);
101 | end;
102 |
103 | function TExecutorCompletitionService.Poll(const ATimeOut: integer): IFuture;
104 | begin
105 | Result := FCompletitionQueue.Poll(ATimeOut) as IFuture;
106 | end;
107 |
108 | function TExecutorCompletitionService.Poll: IFuture;
109 | begin
110 | Result := FCompletitionQueue.Poll() as IFuture;
111 | end;
112 |
113 | function TExecutorCompletitionService.Submit(const ATask: IRunnable;
114 | var AResult: pointer): IFuture;
115 | var
116 | LTask: ITaskFuture;
117 | begin
118 | if not Assigned(ATask) then raise ENullPointer.Create();
119 | LTask := NewTaskFor(ATask, AResult);
120 | FExecutor.Execute(TQueueingFuture.Create(Self, LTask));
121 | Result := LTask as IFuture;
122 | end;
123 |
124 | function TExecutorCompletitionService.Submit(
125 | const ACallable: ICallable): IFuture;
126 | var
127 | LTask: ITaskFuture;
128 | begin
129 | if not Assigned(ACallable) then raise ENullPointer.Create();
130 | LTask := NewTaskFor(ACallable);
131 | FExecutor.Execute(TQueueingFuture.Create(Self, LTask));
132 | Result := LTask as IFuture;
133 | end;
134 |
135 | function TExecutorCompletitionService.Take: IFuture;
136 | begin
137 | Result := FCompletitionQueue.Take() as IFuture;
138 | end;
139 |
140 | end.
141 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/ExecutorService.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit ExecutorService;
12 |
13 | interface
14 |
15 | uses
16 | Future, Callable, Runnable;
17 |
18 | type
19 | IExecutorService = interface
20 | ['{8E517AF7-5086-4C56-8CF4-79B3F47AF275}']
21 | procedure Shutdown;
22 | function ShutdownNow: TRunnableArray;
23 | function IsShutdown: boolean;
24 | function IsTerminated: boolean;
25 | function AwaitTermination(const ATimeOut: int64): boolean;
26 |
27 | function Submit(const ATask: ICallable): IFuture; overload;
28 | function Submit(const ATask: IRunnable; var AResult: pointer): IFuture; overload;
29 | function Submit(const ATask: IRunnable): IFuture; overload;
30 | function InvokeAll(const ATasks: TCallableList): TFutureList; overload;
31 | function InvokeAll(const ATasks: TCallableList; ATimeOut: Int64): TFutureList; overload;
32 | procedure InvokeAny(const ATasks: TCallableList; out AResult: pointer); overload;
33 | procedure InvokeAny(const ATask: TCallableList; ATimeOut: Int64; out AResult: pointer); overload;
34 | end;
35 |
36 | implementation
37 |
38 | end.
39 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Executors.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Executors;
12 |
13 | interface
14 |
15 | uses
16 | ExecutorService, Callable, Runnable;
17 |
18 | type
19 | TExecutors = class
20 | private
21 | {$HINTS OFF}
22 | constructor Create();
23 | {$HINTS ON}
24 | public
25 | //Make sure threadpoolexecutor has shutdown before destruction
26 | class function CreateFixedThreadPool(const ANThreads: integer): IExecutorService; static;
27 | class function Callable(const ATask: IRunnable; out AResult: pointer): ICallable; static;
28 | end;
29 |
30 | implementation
31 |
32 | uses
33 | Exceptions, ThreadPoolExecutor, BlockingQueue;
34 |
35 | type
36 | TRunnableAdapter = class(TInterfacedObject, ICallable)
37 | private
38 | FTask: IRunnable;
39 | FResult: pointer;
40 | public
41 | constructor Create(const ATask: IRunnable; out AResult: pointer);
42 | procedure Call(out AResult: pointer);
43 | end;
44 |
45 | { TExecutors }
46 |
47 | class function TExecutors.Callable(const ATask: IRunnable; out AResult: pointer): ICallable;
48 | begin
49 | if not Assigned(ATask) then raise ENullPointer.Create();
50 | Result := TRunnableAdapter.Create(ATask, AResult);
51 | end;
52 |
53 | constructor TExecutors.Create;
54 | begin
55 | end;
56 |
57 | class function TExecutors.CreateFixedThreadPool(
58 | const ANThreads: integer): IExecutorService;
59 | var
60 | LExecutor: TThreadPoolExecutor;
61 | begin
62 | LExecutor := TThreadPoolExecutor.Create(ANThreads,
63 | ANThreads,
64 | 0,
65 | TInterfaceBlockingQueue.Create(MaxInt));
66 | LExecutor.OwnedQueue := true;
67 | Result := LExecutor;
68 | end;
69 |
70 | { TTaskAdapter }
71 |
72 | procedure TRunnableAdapter.Call(out AResult: pointer);
73 | begin
74 | FTask.Run();
75 | AResult := FResult;
76 | end;
77 |
78 | constructor TRunnableAdapter.Create(const ATask: IRunnable; out AResult: pointer);
79 | begin
80 | FTask := ATask;
81 | AResult := FResult;
82 | end;
83 |
84 | end.
85 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Future.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Future;
12 |
13 | interface
14 |
15 | uses
16 | Classes;
17 |
18 | type
19 | IFuture = interface
20 | ['{7D358C66-F7FD-4A90-9555-7772433C35B5}']
21 | function Cancel(const AInterruptIfRunning: boolean): boolean;
22 | function IsCancelled(): boolean;
23 | function IsDone(): boolean;
24 | procedure GetResult(out AResult: pointer); overload;
25 | procedure GetResult(const ATimeOut: Int64; out AResult: pointer); overload;
26 | end;
27 |
28 | TFutureList = class(TInterfaceList)
29 | end;
30 |
31 | implementation
32 |
33 | end.
34 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/FutureTask.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit FutureTask;
12 |
13 | interface
14 |
15 | uses
16 | RunnableFuture, Callable, Classes, ThreadPoolExecutor, SysUtils, Future,
17 | ExecutorService, Exceptions, Runnable;
18 |
19 | type
20 | TWaitNode = class sealed
21 | strict private
22 | FThreadId: cardinal;
23 | FNext: TWaitNode;
24 | public
25 | constructor Create();
26 |
27 | property ThreadId: cardinal read FThreadId write FThreadId;
28 | property Next: TWaitNode read FNext write FNext;
29 | end;
30 |
31 | TFutureTask = class(TInterfacedObject, ITaskFuture, IRunnable, IFuture)
32 | private
33 | const NEW: byte = 0;
34 | const COMPLETING: byte = 1;
35 | const NORMAL: byte = 2;
36 | const EXCEPTIONAL: byte = 3;
37 | const CANCELLED: byte = 4;
38 | const INTERRUPTING: byte = 5;
39 | const INTERRUPTED: byte = 6;
40 | private
41 | FState: integer;
42 | FCallable: ICallable;
43 | FOutCome: pointer;
44 | FRunner: TThread;
45 | FWaiters: TWaitNode;
46 | private
47 | procedure Report(const AState: byte; out AResult: pointer);
48 | procedure HandlePossibleCancellationInterrupt(const AState: byte);
49 | procedure FinishCompletition();
50 | function AwaitDone(const ATimed: boolean; const ATimeOut: Int64): integer;
51 | procedure RemoveWaiter(const ANode: TWaitNode);
52 | protected
53 | procedure Done(); virtual;
54 | procedure SetResult(var AResult: pointer);
55 | procedure SetException(const E: Exception);
56 | function RunAndReset(): boolean;
57 | public
58 | constructor Create(const ACallable: ICallable); overload;
59 | constructor Create(const ATask: IRunnable; var AResult: pointer); overload;
60 | destructor Destroy(); override;
61 |
62 | //IFuture implementation
63 | function Cancel(const AInterruptIfRunning: boolean): boolean;
64 | function IsCancelled(): boolean;
65 | function IsDone(): boolean;
66 | procedure GetResult(out AResult: pointer); overload;
67 | procedure GetResult(const ATimeOut: Int64; out AResult: pointer); overload;
68 |
69 | //ITaskFuture implementation
70 | procedure Run();
71 | end;
72 |
73 | implementation
74 |
75 | uses
76 | Threading, Executors, DateUtils, Windows, Contnrs, SyncObjs;
77 |
78 | type
79 | TInterlocked = class sealed
80 | public
81 | class function CompareExchange(var ADestination: integer; const AExchange: integer; const AComparand: integer): boolean; static;
82 | class function CompareExchangePointer(var ADestination: pointer; const AExchange: pointer; const AComparand: pointer): boolean; static;
83 | class procedure Exchange(var ATarget: integer; const AValue: integer); static;
84 | class procedure ExchangePointer(var ATarget: pointer; const AValue: pointer); static;
85 | end;
86 |
87 | TLockSuport = class sealed
88 | private type
89 | TParkedList = class(TStringList)
90 | private
91 | class var FInstance: TParkedList;
92 | private
93 | FCriticalSection: TCriticalSection;
94 | public
95 | constructor Create();
96 | destructor Destroy(); override;
97 | procedure Park(const AThreadId: integer);
98 | function IsParked(const AThreadId: integer): boolean;
99 | procedure UnPark(const AThreadId: integer);
100 | class procedure Initialize;
101 | class procedure Finalize;
102 | class function GetInstance: TParkedList;
103 | end;
104 | public
105 | class procedure ParkMilli(const ATimeOut: Int64); static;
106 | class procedure Park(); static;
107 | class procedure UnPark(const AThreadId: integer); static;
108 | end;
109 |
110 | { TFutureTask }
111 |
112 | constructor TFutureTask.Create(const ATask: IRunnable; var AResult: pointer);
113 | begin
114 | FCallable := TExecutors.Callable(ATask, AResult);
115 | FState := NEW;
116 | end;
117 |
118 | constructor TFutureTask.Create(const ACallable: ICallable);
119 | begin
120 | if not Assigned(ACallable) then raise ENullPointer.Create();
121 | FCallable := ACallable;
122 | FState := NEW;
123 | end;
124 |
125 | function TFutureTask.AwaitDone(const ATimed: boolean; const ATimeOut: Int64): integer;
126 | var
127 | LDeadLine: TDateTime;
128 | LQ: TWaitNode;
129 | LQueued: boolean;
130 | LCurThread: TCustomThread;
131 | LState: byte;
132 | LNow: TDateTime;
133 | begin
134 | LDeadLine := MinDateTime;
135 | if ATimed then begin
136 | LDeadLine := Now();
137 | LDeadLine := IncMilliSecond(LDeadLine, ATimeOut);
138 | end;
139 | LQ := nil;
140 | LQueued := false;
141 | while true do begin
142 | LCurThread := TCustomThread.GetCurrentThread() as TCustomThread;
143 | if Assigned(LCurThread) and LCurThread.Interrupted then begin
144 | try
145 | RemoveWaiter(LQ);
146 | finally
147 | FreeAndNil(LQ);
148 | end;
149 | raise EInterrupted.Create();
150 | end;
151 |
152 | LState := FState;
153 | if (LState > COMPLETING) then begin
154 | if Assigned(LQ) then begin
155 | LQ.ThreadId := 0;
156 | FreeAndNil(LQ);
157 | end;
158 | Result := LState;
159 | Exit;
160 | end else if (LState = COMPLETING) then begin
161 | TCustomThread.Yield();
162 | end else if not Assigned(LQ) then begin
163 | LQ := TWaitNode.Create();
164 | end else if not LQueued then begin
165 | LQ.Next := FWaiters;
166 | LQueued := (TInterlocked.CompareExchangePointer(
167 | pointer(FWaiters),
168 | pointer(LQ),
169 | pointer(LQ.Next)));
170 | end else if ATimed then begin
171 | LNow := Now();
172 | if (MilliSecondsBetween(LNow, LDeadLine) <= 0 ) then begin
173 | try
174 | RemoveWaiter(LQ);
175 | finally
176 | FreeAndNil(LQ);
177 | end;
178 | Result := LState;
179 | Exit;
180 | end;
181 | TLockSuport.ParkMilli(ATimeOut);
182 | end else begin
183 | TLockSuport.Park();
184 | end;
185 | end;
186 | end;
187 |
188 | function TFutureTask.Cancel(const AInterruptIfRunning: boolean): boolean;
189 | var
190 | LRunner: TThread;
191 | begin
192 | if (FState <> NEW) then begin
193 | Result := false;
194 | Exit;
195 | end else if AInterruptIfRunning then begin
196 | if not TInterlocked.CompareExchange(FState, INTERRUPTING, NEW) then begin
197 | Result := false;
198 | Exit;
199 | end;
200 |
201 | LRunner := FRunner;
202 | if Assigned(LRunner) then TCustomThread(LRunner).Interrupt();
203 |
204 | TInterlocked.Exchange(FState, INTERRUPTED);
205 | end else if (not TInterlocked.CompareExchange(FState, CANCELLED, NEW)) then begin
206 | Result := false;
207 | Exit;
208 | end;
209 | FinishCompletition();
210 | Result := true;
211 | end;
212 |
213 | destructor TFutureTask.Destroy;
214 | begin
215 | inherited;
216 | end;
217 |
218 | procedure TFutureTask.Done;
219 | begin
220 | //
221 | end;
222 |
223 | procedure TFutureTask.Run;
224 | var
225 | LState: Integer;
226 | LCallable: ICallable;
227 | LResult: Pointer;
228 | LRan: Boolean;
229 | begin
230 | if (FState <> NEW) or (not TInterlocked.CompareExchangePointer(
231 | pointer(FRunner),
232 | pointer(TCustomThread.GetCurrentThread()),
233 | nil)) then begin
234 | Exit;
235 | end;
236 | try
237 | LCallable := FCallable;
238 | LResult := nil;
239 | try
240 | LCallable.Call(LResult);
241 | LRan := true;
242 | except
243 | on E: Exception do begin
244 | LResult := nil;
245 | LRan := false;
246 | SetException(Exception(AcquireExceptionObject()));
247 | end;
248 | end;
249 | if LRan then SetResult(LResult);
250 | finally
251 | FRunner := nil;
252 | LState := FState;
253 | if (LState <> INTERRUPTING) then HandlePossibleCancellationInterrupt(LState);
254 | end;
255 | end;
256 |
257 | procedure TFutureTask.FinishCompletition;
258 | var
259 | LQ: TWaitNode;
260 | LThreadId: cardinal;
261 | LNext: TWaitNode;
262 | begin
263 | LQ := FWaiters;
264 | while Assigned(LQ) do begin
265 | if (TInterlocked.CompareExchangePointer(pointer(FWaiters),
266 | nil,
267 | pointer(LQ))) then begin
268 | while true do begin
269 | LThreadId := LQ.ThreadId;
270 | if (LThreadId > 0) then begin
271 | LQ.ThreadId := 0;
272 | TLockSuport.UnPark(LThreadId);
273 | end;
274 | LNext := LQ.Next;
275 | if not Assigned(LNext) then begin
276 | Break;
277 | end;
278 | LQ.Next := nil;
279 | LQ := LNext;
280 | end;
281 | Break;
282 | end;
283 | end;
284 | done();
285 | FCallable := nil;
286 | end;
287 |
288 | procedure TFutureTask.GetResult(out AResult: pointer);
289 | var
290 | LState: Integer;
291 | begin
292 | LState := FState;
293 | if (LState <= COMPLETING) then begin
294 | LState := AwaitDone(false, 0);
295 | end;
296 | Report(LState, AResult);
297 | end;
298 |
299 | procedure TFutureTask.GetResult(const ATimeOut: Int64; out AResult: pointer);
300 | var
301 | LState: Integer;
302 | begin
303 | LState := FState;
304 | if (LState <= COMPLETING) then begin
305 | LState := AwaitDone(true, ATimeOut);
306 | if (LState <= COMPLETING) then raise ETimeOut.Create();
307 | end;
308 | Report(LState, AResult);
309 | end;
310 |
311 | procedure TFutureTask.HandlePossibleCancellationInterrupt(const AState: byte);
312 | begin
313 | if (AState = INTERRUPTING) then begin
314 | while (FState = INTERRUPTING) do begin
315 | TCustomThread.Yield;
316 | end;
317 | end;
318 | end;
319 |
320 | function TFutureTask.IsCancelled: boolean;
321 | begin
322 | Result := FState >= CANCELLED;
323 | end;
324 |
325 | function TFutureTask.IsDone: boolean;
326 | begin
327 | Result := FState <> NEW;
328 | end;
329 |
330 | procedure TFutureTask.RemoveWaiter(const ANode: TWaitNode);
331 | label
332 | LRetry;
333 | var
334 | LPred: TWaitNode;
335 | LQ: TWaitNode;
336 | LS: TWaitNode;
337 | begin
338 | if Assigned(ANode) then begin
339 | ANode.ThreadId := 0;
340 |
341 | LRetry:
342 | while true do begin
343 | LPred := nil;
344 | LQ := FWaiters;
345 | while Assigned(LQ) do begin
346 | LS := LQ.Next;
347 | if (LQ.ThreadId > 0) then begin
348 | LPred := LQ;
349 | end else if Assigned(LPred) then begin
350 | LPred.Next := LS;
351 | if not (LPred.ThreadId > 0) then begin
352 | goto LRetry;
353 | end;
354 | end else if (not TInterlocked.CompareExchangePointer(
355 | pointer(FWaiters),
356 | LS,
357 | LQ)) then begin
358 | goto LRetry;
359 | end;
360 | LQ := LS;
361 | end;
362 | Break;
363 | end;
364 | end;
365 | end;
366 |
367 | procedure TFutureTask.Report(const AState: byte; out AResult: pointer);
368 | begin
369 | if (AState = NORMAL) then begin
370 | AResult := FOutCome;
371 | end else if (AState = CANCELLED) then begin
372 | raise ECancellation.Create('Task cancelled.');
373 | end else begin
374 | raise Exception(FOutCome);
375 | end;
376 | end;
377 |
378 | function TFutureTask.RunAndReset: boolean;
379 | var
380 | LRan: boolean;
381 | LState: byte;
382 | LCallable: ICallable;
383 | LNil: pointer;
384 | begin
385 | if (FState <> NEW) or (not TInterlocked.CompareExchangePointer(
386 | pointer(FRunner),
387 | pointer(TCustomThread.GetCurrentThread()),
388 | nil)) then begin
389 | Result := false;
390 | Exit;
391 | end;
392 | LRan := false;
393 | LState := FState;
394 | try
395 | LCallable := FCallable;
396 | if Assigned(FCallable) and (LState = NEW) then begin
397 | try
398 | LNil := nil;
399 | LCallable.Call(LNil);
400 | LRan := true;
401 | except
402 | on E: Exception do begin
403 | SetException(Exception(AcquireExceptionObject()));
404 | end;
405 | end;
406 | end;
407 | finally
408 | LState := FState;
409 | if (LState >= INTERRUPTING) then begin
410 | HandlePossibleCancellationInterrupt(LState);
411 | end;
412 | end;
413 | Result := LRan and (LState = NEW);
414 | end;
415 |
416 | procedure TFutureTask.SetException(const E: Exception);
417 | begin
418 | if (TInterlocked.CompareExchange(FState, COMPLETING, NEW)) then begin
419 | FOutCome := pointer(E);
420 | TInterlocked.Exchange(FState, EXCEPTIONAL);
421 | FinishCompletition();
422 | end;
423 | end;
424 |
425 | procedure TFutureTask.SetResult(var AResult: pointer);
426 | begin
427 | if (TInterlocked.CompareExchange(FState, COMPLETING, NEW)) then begin
428 | FOutCome := AResult;
429 | TInterlocked.Exchange(FState, NORMAL);
430 | FinishCompletition();
431 | end;
432 | end;
433 |
434 | { TWaitNode }
435 |
436 | constructor TWaitNode.Create;
437 | begin
438 | FThreadId := GetCurrentThreadId();
439 | end;
440 |
441 | { TInterlocked }
442 |
443 | class function TInterlocked.CompareExchange(var ADestination: integer;
444 | const AExchange, AComparand: integer): boolean;
445 | begin
446 | Result := Windows.InterlockedCompareExchange(ADestination,
447 | AExchange,
448 | AComparand) = AComparand;
449 | end;
450 |
451 | class function TInterlocked.CompareExchangePointer(var ADestination: pointer;
452 | const AExchange, AComparand: pointer): boolean;
453 | begin
454 | Result := Windows.InterlockedCompareExchange(integer(ADestination),
455 | integer(AExchange),
456 | integer(AComparand))
457 | = integer(AComparand);
458 | end;
459 |
460 | class procedure TInterlocked.Exchange(var ATarget: integer;
461 | const AValue: integer);
462 | begin
463 | Windows.InterlockedExchange(ATarget, AValue);
464 | end;
465 |
466 | class procedure TInterlocked.ExchangePointer(var ATarget: pointer;
467 | const AValue: pointer);
468 | begin
469 | Windows.InterlockedExchange(integer(ATarget), integer(AValue));
470 | end;
471 |
472 | { TLockSuport }
473 |
474 | class procedure TLockSuport.Park();
475 | var
476 | LThreadId: Cardinal;
477 | begin
478 | LThreadId := GetCurrentThreadId();
479 | TParkedList.GetInstance().Park(LThreadId);
480 | try
481 | while TParkedList.GetInstance().IsParked(LThreadId) do begin
482 | SleepEx(100, true);
483 | end;
484 | except
485 | on E: Exception do begin
486 | TParkedList.GetInstance().UnPark(LThreadId);
487 | raise;
488 | end;
489 | end;
490 | end;
491 |
492 | class procedure TLockSuport.ParkMilli(const ATimeOut: Int64);
493 | var
494 | LThreadId: cardinal;
495 | LDeadLine: TDateTime;
496 | LNow: TDateTime;
497 | begin
498 | LThreadId := GetCurrentThreadId();
499 | TParkedList.GetInstance().Park(LThreadId);
500 | try
501 | LNow := Now();
502 | LDeadLine := IncMilliSecond(LNow, ATimeOut);
503 | try
504 | while (MilliSecondsBetween(LNow, LDeadLine) > 0)
505 | and TParkedList.GetInstance().IsParked(LThreadId) do begin
506 | SleepEx(100, true);
507 | LNow := Now();
508 | end;
509 | finally
510 | TParkedList.GetInstance().UnPark(LThreadId);
511 | end;
512 | except
513 | on E: Exception do begin
514 | TParkedList.GetInstance().UnPark(LThreadId);
515 | raise;
516 | end;
517 | end;
518 | end;
519 |
520 | class procedure TLockSuport.UnPark(const AThreadId: integer);
521 | begin
522 | TParkedList.GetInstance().UnPark(AThreadId);
523 | end;
524 |
525 | { TLockSuport.TParkedList }
526 |
527 | constructor TLockSuport.TParkedList.Create;
528 | begin
529 | inherited Create();
530 | FCriticalSection := TCriticalSection.Create();
531 | Self.Duplicates := dupError;
532 | Self.Sorted := true;
533 | end;
534 |
535 | destructor TLockSuport.TParkedList.Destroy;
536 | begin
537 | FCriticalSection.Free();
538 | inherited;
539 | end;
540 |
541 | class procedure TLockSuport.TParkedList.Finalize;
542 | begin
543 | FreeAndNil(FInstance);
544 | end;
545 |
546 | class function TLockSuport.TParkedList.GetInstance: TParkedList;
547 | begin
548 | Result := FInstance;
549 | end;
550 |
551 | class procedure TLockSuport.TParkedList.Initialize;
552 | begin
553 | if not Assigned(FInstance) then
554 | FInstance := TParkedList.Create();
555 | end;
556 |
557 | function TLockSuport.TParkedList.IsParked(const AThreadId: integer): boolean;
558 | begin
559 | FCriticalSection.Acquire;
560 | try
561 | Result := Self.IndexOf(IntToStr(AThreadId)) > -1;
562 | finally
563 | FCriticalSection.Leave;
564 | end;
565 | end;
566 |
567 | procedure TLockSuport.TParkedList.Park(const AThreadId: integer);
568 | begin
569 | FCriticalSection.Acquire;
570 | try
571 | Self.Add(IntToStr(AThreadId));
572 | finally
573 | FCriticalSection.Leave;
574 | end;
575 | end;
576 |
577 | procedure TLockSuport.TParkedList.UnPark(const AThreadId: integer);
578 | begin
579 | FCriticalSection.Acquire;
580 | try
581 | if Self.IndexOf(IntToStr(AThreadId)) > -1 then
582 | Self.Delete(Self.IndexOf(IntToStr(AThreadId)));
583 | finally
584 | FCriticalSection.Leave;
585 | end;
586 | end;
587 |
588 | initialization
589 | TLockSuport.TParkedList.Initialize;
590 |
591 | finalization
592 | TLockSuport.TParkedList.Finalize;
593 |
594 | end.
595 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Runnable.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Runnable;
12 |
13 | interface
14 |
15 | type
16 | //Runnable - The Command
17 | IRunnable = interface
18 | ['{C51BDF40-3359-4FD2-809A-322BDD637C60}']
19 | procedure Run();
20 | end;
21 |
22 | TRunnableArray = array of IRunnable;
23 |
24 | implementation
25 |
26 | end.
27 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/RunnableFuture.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit RunnableFuture;
12 |
13 | interface
14 |
15 | uses
16 | Runnable;
17 |
18 | type
19 | ITaskFuture = interface(IRunnable)
20 | ['{201A1063-24E5-4453-B3BD-5270AE18BE17}']
21 | procedure Run();
22 | end;
23 |
24 | implementation
25 |
26 | end.
27 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/ThreadPoolExecutor.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit ThreadPoolExecutor;
12 |
13 | interface
14 |
15 | uses
16 | Classes,
17 | SysUtils,
18 | Contnrs,
19 | SyncObjs, BlockingQueue, Threading, ExecutorService, AbstractExecutorService,
20 | Runnable;
21 |
22 | type
23 | TWorker = class;
24 |
25 | TThreadPooled = class;
26 |
27 | IThreadPooledFactory = interface
28 | ['{8CAC8A6A-34E7-40D6-9CE6-6A45C78D2BCD}']
29 | function CreateThread(const AWorker: TWorker): TThreadPooled;
30 | end;
31 |
32 | IRejectedExecutionHandler = interface;
33 |
34 | TThreadPoolExecutor = class(TAbstractExecutorService)
35 | private
36 | FWorkers: TObjectList;
37 | FWorkQueue: TInterfaceBlockingQueue;
38 | FLock:TCriticalSection;
39 | FLargestPoolSize: integer;
40 | FCompletedTaskCount: integer;
41 | FPoolSize:integer;
42 | FKeepAliveTime: integer;
43 | FAllowCoreThreadTimeOut: boolean;
44 | FCorePoolSize: integer;
45 | FMaximumPoolSize: integer;
46 | FRunState: byte;
47 | FThreadPooledFactory: IThreadPooledFactory;
48 | FRejectedExecutionHandler: IRejectedExecutionHandler;
49 | FOwnedQueue: boolean;
50 | private
51 | const STATE_RUNNING = 0;
52 | const STATE_SHUTDOWN = 1;
53 | const STATE_STOP = 2;
54 | const STATE_TERMINATED = 3;
55 | strict private
56 | procedure SetMaximumPoolSize(val : Integer);
57 | procedure SetCorePoolSize(val : Integer);
58 | procedure SetKeepAliveTime(val : Integer);
59 | procedure SetRejectedExecutionHandler(const Value: IRejectedExecutionHandler);
60 | procedure SetAllowCoreThreadTimeOut(const Value: boolean);
61 | procedure SetThreadPooledFactory(const Value: IThreadPooledFactory);
62 | function GetLargestPoolSize: integer;
63 | private
64 | function AddThread(const AFirstTask: IRunnable): TThread;
65 | function AddIfUnderCorePoolSize(const AFirstTask: IRunnable): boolean;
66 | function AddIfUnderMaximumPoolSize(const AFirstTask: IRunnable): integer;
67 | procedure InterruptIdleWorkers;
68 | procedure WorkerDone(const AWorker: TWorker);
69 | procedure Reject(const ATask: IRunnable);
70 | protected
71 | function GetTask: IRunnable;
72 | procedure BeforeExecute(const AThread: TThread; const ATask: IRunnable); virtual;
73 | procedure AfterExecute(const ATask: IRunnable; const AException: Exception); virtual;
74 | procedure Terminated; virtual;
75 | public
76 | constructor Create(const ACorePoolSize, AMaximumPoolSize, AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue);overload;
77 | constructor Create(const ACorePoolSize, AMaximumPoolSize, AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue; const AThreadFactory: IThreadPooledFactory);overload;
78 | constructor Create(const ACorePoolSize, AMaximumPoolSize, AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue; const AThreadFactory: IThreadPooledFactory; const ARejectedExecutionHandler: IRejectedExecutionHandler);overload;
79 | destructor Destroy(); override;
80 |
81 | procedure Execute(const ATask: IRunnable); override;
82 | function Remove(const ATask: IRunnable): boolean;
83 |
84 | procedure Shutdown; override;
85 | function ShutdownNow: TRunnableArray; override;
86 | function IsShutdown: boolean; override;
87 | function IsTerminated: boolean; override;
88 | function AwaitTermination(const ATimeout: int64): boolean; override;
89 | function IsTerminating: boolean;
90 | function PrestartCoreThread: boolean;
91 | function PrestartAllCoreThreads: integer;
92 | function GetActiveCount: integer;
93 | function GetTaskCount: integer;
94 | function GetCompletedTaskCount: integer;
95 |
96 | property ThreadFactory: IThreadPooledFactory read FThreadPooledFactory write SetThreadPooledFactory;
97 | property RejectedExecutionHandler: IRejectedExecutionHandler read FRejectedExecutionHandler write SetRejectedExecutionHandler;
98 | property KeepAliveTime : Integer read FKeepAliveTime write SetKeepAliveTime;
99 | property CorePoolSize : Integer read FCorePoolSize write SetCorePoolSize;
100 | property MaximumPoolSize : Integer read FMaximumPoolSize write SetMaximumPoolSize;
101 | property AllowsCoreThreadTimeOut: boolean read FAllowCoreThreadTimeOut write SetAllowCoreThreadTimeOut;
102 | property PoolSize: integer read FPoolSize;
103 | property LargestPoolSize: integer read GetLargestPoolSize;
104 | property Queue: TInterfaceBlockingQueue read FWorkQueue;
105 | property OwnedQueue: boolean read FOwnedQueue write FOwnedQueue default false;
106 | end;
107 |
108 | TThreadPooled = class(TCustomThread)
109 | private
110 | FWorker: TWorker;
111 | FException: TObject;
112 | procedure DoHandleException;
113 | protected
114 | procedure HandleException; virtual;
115 | procedure Execute; override;
116 | public
117 | constructor Create(const AWorker: TWorker);
118 | destructor Destroy(); override;
119 | end;
120 |
121 | TDefaultThreadPooledFactory = class(TInterfacedObject, IThreadPooledFactory)
122 | public
123 | constructor Create();
124 | destructor Destroy(); override;
125 |
126 | function CreateThread(const AWorker: TWorker): TThreadPooled;
127 | end;
128 |
129 | IRejectedExecutionHandler = interface
130 | ['{B75598D2-ABC4-42BF-92E9-B7207318603D}']
131 | procedure RejectedExecution(const ATask: IRunnable; const APool: TThreadPoolExecutor);
132 | end;
133 |
134 | TCallerRunsPolicy = class(TInterfacedObject, IRejectedExecutionHandler)
135 | public
136 | procedure RejectedExecution(const ATask: IRunnable; const APool: TThreadPoolExecutor);
137 | end;
138 |
139 | TAbortPolicy = class(TInterfacedObject, IRejectedExecutionHandler)
140 | public
141 | procedure RejectedExecution(const ATask: IRunnable; const APool: TThreadPoolExecutor);
142 | end;
143 |
144 | TDiscardPolicy = class(TInterfacedObject, IRejectedExecutionHandler)
145 | public
146 | procedure RejectedExecution(const ATask: IRunnable; const APool: TThreadPoolExecutor);
147 | end;
148 |
149 | TDiscardOldestPolicy = class(TInterfacedObject, IRejectedExecutionHandler)
150 | public
151 | procedure RejectedExecution(const ATask: IRunnable; const APool: TThreadPoolExecutor);
152 | end;
153 |
154 | TWorker = class
155 | strict private var
156 | FThread:TThreadPooled;
157 | FThreadPool:TThreadPoolExecutor;
158 | FLock: TCriticalSection;
159 | FFirstTask: IRunnable;
160 | FCompletedTasks: integer;
161 | private
162 | procedure SetThread(const Value: TThreadPooled);
163 | procedure RunTask(const ATask: IRunnable);
164 | public
165 | constructor Create(const AThreadPool: TThreadPoolExecutor; const AFirstTask: IRunnable); overload;
166 | constructor Create(const AFirstTask: IRunnable); overload;
167 | destructor Destroy(); override;
168 |
169 | function IsActive(): boolean;
170 | procedure InterruptIfIdle;
171 | procedure InterruptNow;
172 |
173 | procedure Run();
174 |
175 | property ThreadPool: TThreadPoolExecutor read FThreadPool write FThreadPool;
176 | property Thread: TThreadPooled read FThread write SetThread;
177 | property CompletedTasks: integer read FCompletedTasks;
178 | end;
179 |
180 | implementation
181 |
182 | uses
183 | Windows, Exceptions, Messages;
184 |
185 | { TThreadPool }
186 |
187 | function TThreadPoolExecutor.AddIfUnderCorePoolSize(const AFirstTask: IRunnable): boolean;
188 | var
189 | LThread: TThread;
190 | begin
191 | LThread := nil;
192 | FLock.Acquire();
193 | try
194 | if (FPoolSize < FCorePoolSize) then LThread := AddThread(AFirstTask);
195 | finally
196 | FLock.Release();
197 | end;
198 | if not Assigned(LThread) then begin
199 | Result := false;
200 | end else begin
201 | LThread.Resume();
202 | Result := true;
203 | end;
204 | end;
205 |
206 | function TThreadPoolExecutor.AddIfUnderMaximumPoolSize(
207 | const AFirstTask: IRunnable): integer;
208 | var
209 | LThread: TThread;
210 | LStatus: Integer;
211 | LNext: IRunnable;
212 | begin
213 | LThread := nil;
214 | LStatus := 0;
215 | FLock.Acquire();
216 | try
217 | if (FPoolSize < FMaximumPoolSize) then begin
218 | LNext := IRunnable(FWorkQueue.Poll());
219 | if not Assigned(LNext) then begin
220 | LNext := AFirstTask;
221 | LStatus := 1;
222 | end else begin
223 | LStatus := -1;
224 | end;
225 | LThread := AddThread(LNext);
226 | end;
227 | finally
228 | FLock.Release();
229 | end;
230 | if not Assigned(LThread) then begin
231 | LStatus := 0;
232 | end else begin
233 | LThread.Resume();
234 | end;
235 | Result := LStatus;
236 | end;
237 |
238 | function TThreadPoolExecutor.AddThread(const AFirstTask: IRunnable): TThread;
239 | var
240 | LWorker: TWorker;
241 | LThread: TThreadPooled;
242 | begin
243 | Result := nil;
244 | if (FRunState = STATE_TERMINATED) then begin
245 | Exit;
246 | end;
247 | LWorker := TWorker.Create(Self, AFirstTask);
248 | LThread := FThreadPooledFactory.CreateThread(LWorker);
249 | if Assigned(LThread) then begin
250 | LWorker.Thread := LThread;
251 | FWorkers.Add(LWorker);
252 | Inc(FPoolSize);
253 | if (FPoolSize > FLargestPoolSize) then FLargestPoolSize := FPoolSize;
254 | Result := LThread;
255 | end;
256 | end;
257 |
258 | function TThreadPoolExecutor.AwaitTermination(const ATimeout: int64): boolean;
259 | const
260 | PERCENTAGE = 10;
261 | var
262 | LTimeOut: Integer;
263 | LPartiality: Integer;
264 | begin
265 | Result := false;
266 | LTimeOut := ATimeout;
267 | FLock.Acquire();
268 | try
269 | LPartiality := Round(PERCENTAGE * LTimeOut / 100);
270 | while true do begin
271 | if (FRunState = STATE_TERMINATED) then begin
272 | Result := true;
273 | Break;
274 | end;
275 | if (LTimeOut <= 0) then begin
276 | Result := false;
277 | Break;
278 | end;
279 |
280 | //Sleeps PERCENTAGE of total timeout at a time
281 | SleepEx(LPartiality, true);
282 |
283 | LTimeOut := LTimeOut - LPartiality;
284 | end;
285 | finally
286 | FLock.Release();
287 | end;
288 | end;
289 |
290 | procedure TThreadPoolExecutor.AfterExecute(const ATask: IRunnable;
291 | const AException: Exception);
292 | begin
293 | //
294 | end;
295 |
296 | procedure TThreadPoolExecutor.BeforeExecute(const AThread: TThread; const ATask: IRunnable);
297 | begin
298 | //
299 | end;
300 |
301 | constructor TThreadPoolExecutor.Create(const ACorePoolSize, AMaximumPoolSize,
302 | AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue);
303 | begin
304 | Create(ACorePoolSize, AMaximumPoolSize, AKeepAliveTime, AWorkQueue, TDefaultThreadPooledFactory.Create());
305 | end;
306 |
307 | constructor TThreadPoolExecutor.Create(const ACorePoolSize, AMaximumPoolSize,
308 | AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue;
309 | const AThreadFactory: IThreadPooledFactory);
310 | begin
311 | Create(ACorePoolSize, AMaximumPoolSize, AKeepAliveTime, AWorkQueue,
312 | AThreadFactory,
313 | TAbortPolicy.Create());
314 | end;
315 |
316 | constructor TThreadPoolExecutor.Create(const ACorePoolSize, AMaximumPoolSize,
317 | AKeepAliveTime: integer; const AWorkQueue: TInterfaceBlockingQueue;
318 | const AThreadFactory: IThreadPooledFactory;
319 | const ARejectedExecutionHandler: IRejectedExecutionHandler);
320 | begin
321 | if (ACorePoolSize < 0)
322 | or (AMaximumPoolSize <= 0)
323 | or (AMaximumPoolSize < ACorePoolSize)
324 | or (AKeepAliveTime < 0) then raise EInvalidParameters.Create();
325 |
326 | if not Assigned(AWorkQueue)
327 | or not Assigned(AThreadFactory)
328 | or not Assigned(ARejectedExecutionHandler) then raise ENullPointer.Create;
329 |
330 | inherited Create();
331 | FCorePoolSize := ACorePoolSize;
332 | FMaximumPoolSize := AMaximumPoolSize;
333 | FKeepAliveTime := AKeepAliveTime;
334 | FWorkQueue := AWorkQueue;
335 | FThreadPooledFactory := AThreadFactory;
336 | FRejectedExecutionHandler := ARejectedExecutionHandler;
337 |
338 | FWorkers:= TObjectList.Create(true);
339 | FLock := TCriticalSection.Create;
340 | FPoolSize := 0;
341 | FAllowCoreThreadTimeOut:= false;
342 | FLargestPoolSize:= 0;
343 | FRunState:= 0;
344 | FCompletedTaskCount:= 0;
345 | FOwnedQueue := false;
346 | end;
347 |
348 | destructor TThreadPoolExecutor.Destroy;
349 | begin
350 | Shutdown;
351 | FWorkers.Free;
352 | FLock.Free;
353 | if FOwnedQueue then FreeAndNil(FWorkQueue);
354 | inherited;
355 | end;
356 |
357 | procedure TThreadPoolExecutor.Execute(const ATask: IRunnable);
358 | var
359 | LStatus: integer;
360 | begin
361 | if not Assigned(ATask) then raise ENullPointer.Create;
362 |
363 | while true do begin
364 | if (FRunState <> STATE_RUNNING) then begin
365 | Reject(ATask);
366 | Break;
367 | end;
368 |
369 | if (FPoolSize < FCorePoolSize) and AddIfUnderCorePoolSize(ATask) then begin
370 | Break;
371 | end;
372 |
373 | if (FWorkQueue.Offer(ATask)) then Break;
374 |
375 | LStatus := AddIfUnderMaximumPoolSize(ATask);
376 | if (LStatus > 0) then Exit;
377 | if (LStatus = 0) then begin
378 | Reject(ATask);
379 | Break;
380 | end;
381 | end;
382 | end;
383 |
384 | function TThreadPoolExecutor.GetActiveCount: integer;
385 | var
386 | LCount: Integer;
387 | LWorker: Pointer;
388 | begin
389 | FLock.Acquire();
390 | try
391 | LCount := 0;
392 | for LWorker in FWorkers do begin
393 | if (TWorker(LWorker)).IsActive() then begin
394 | Inc(LCount);
395 | end;
396 | end;
397 | Result := LCount;
398 | finally
399 | FLock.Release();
400 | end;
401 | end;
402 |
403 | function TThreadPoolExecutor.GetCompletedTaskCount: integer;
404 | var
405 | LCompleted: Integer;
406 | LWorker: Pointer;
407 | begin
408 | FLock.Acquire();
409 | try
410 | LCompleted := FCompletedTaskCount;
411 | for LWorker in FWorkers do begin
412 | LCompleted := LCompleted + TWorker(LWorker).CompletedTasks;
413 | end;
414 | Result := LCompleted;
415 | finally
416 | FLock.Release();
417 | end;
418 | end;
419 |
420 | function TThreadPoolExecutor.GetLargestPoolSize: integer;
421 | begin
422 | FLock.Acquire();
423 | try
424 | Result := FLargestPoolSize;
425 | finally
426 | FLock.Release();
427 | end;
428 | end;
429 |
430 | function TThreadPoolExecutor.GetTask: IRunnable;
431 | var
432 | LTimeOut: Integer;
433 | LTask: IRunnable;
434 | begin
435 | while true do begin
436 | try
437 | case FRunState of
438 | STATE_RUNNING: begin
439 | if (FPoolSize <= FCorePoolSize) and (not FAllowCoreThreadTimeOut) then begin
440 | Result := IRunnable(FWorkQueue.Take());
441 | Exit;
442 | end;
443 |
444 | LTimeOut := FKeepAliveTime;
445 | if (LTimeOut <= 0) then begin
446 | Result := nil;
447 | Exit;
448 | end;
449 |
450 | LTask := IRunnable(FWorkQueue.Poll(LTimeOut));
451 | if Assigned(LTask) then begin
452 | Result := LTask;
453 | Exit;
454 | end;
455 |
456 | if (FPoolSize > FCorePoolSize) or (FAllowCoreThreadTimeOut) then begin
457 | Result := nil; //timed out
458 | Exit;
459 | end;
460 |
461 | Result := nil;
462 | Break;
463 | end;
464 | STATE_SHUTDOWN: begin
465 | LTask := IRunnable(FWorkQueue.Poll());
466 | if Assigned(LTask) then begin
467 | Result := LTask;
468 | Exit;
469 | end;
470 |
471 | if FWorkQueue.IsEmpty then begin
472 | InterruptIdleWorkers();
473 | Result := nil;
474 | Break;
475 | end;
476 |
477 | Result := IRunnable(FWorkQueue.Take());
478 | end;
479 | STATE_STOP: begin
480 | Result := nil;
481 | Exit;
482 | end;
483 | else begin
484 | Assert(false, 'Invalid state.');
485 | end;
486 | end;
487 | except
488 | on E: EInterrupted do begin
489 | //
490 | end else raise;
491 | end;
492 | end;
493 | end;
494 |
495 | function TThreadPoolExecutor.GetTaskCount: integer;
496 | var
497 | LCompleted: integer;
498 | LWorker: Pointer;
499 | begin
500 | FLock.Acquire();
501 | try
502 | LCompleted := FCompletedTaskCount;
503 | for LWorker in FWorkers do begin
504 | LCompleted := LCompleted + TWorker(LWorker).CompletedTasks;
505 | if (TWorker(LWorker).IsActive) then Inc(LCompleted);
506 | end;
507 | Result := LCompleted + FWorkQueue.Count;
508 | finally
509 | FLock.Release();
510 | end;
511 | end;
512 |
513 | procedure TThreadPoolExecutor.InterruptIdleWorkers;
514 | var
515 | LItem: Pointer;
516 | begin
517 | FLock.Acquire();
518 | try
519 | for LItem in FWorkers do begin
520 | TWorker(LItem).InterruptIfIdle();
521 | end;
522 | finally
523 | FLock.Release();
524 | end;
525 | end;
526 |
527 | function TThreadPoolExecutor.IsShutdown: boolean;
528 | begin
529 | Result := FRunState <> STATE_RUNNING;
530 | end;
531 |
532 | function TThreadPoolExecutor.IsTerminated: boolean;
533 | begin
534 | Result := FRunState = STATE_TERMINATED;
535 | end;
536 |
537 | function TThreadPoolExecutor.IsTerminating: boolean;
538 | begin
539 | Result := FRunState = STATE_STOP;
540 | end;
541 |
542 | function TThreadPoolExecutor.PrestartAllCoreThreads: integer;
543 | var
544 | LCount: Integer;
545 | begin
546 | LCount := 0;
547 | while (AddIfUnderCorePoolSize(nil)) do Inc(LCount);
548 | Result := LCount;
549 | end;
550 |
551 | function TThreadPoolExecutor.PrestartCoreThread: boolean;
552 | begin
553 | Result := AddIfUnderCorePoolSize(nil);
554 | end;
555 |
556 | procedure TThreadPoolExecutor.Reject(const ATask: IRunnable);
557 | begin
558 | FRejectedExecutionHandler.RejectedExecution(ATask, Self);
559 | end;
560 |
561 | function TThreadPoolExecutor.Remove(const ATask: IRunnable): boolean;
562 | begin
563 | Result := FWorkQueue.Remove(ATask);
564 | end;
565 |
566 | procedure TThreadPoolExecutor.SetAllowCoreThreadTimeOut(const Value: boolean);
567 | begin
568 | if (Value and (FKeepAliveTime <= 0)) then begin
569 | raise ECoreThreadNonZeroKeepAliveTime.Create();
570 | end;
571 | FAllowCoreThreadTimeOut := Value;
572 | end;
573 |
574 | procedure TThreadPoolExecutor.SetCorePoolSize(val: Integer);
575 | var
576 | LExtra: Integer;
577 | LSize: Integer;
578 | LThread: TThread;
579 | LIx: integer;
580 | begin
581 | if (val < 0) then raise EInvalidParameters.Create();
582 |
583 | FLock.Acquire();
584 | try
585 | LExtra := FCorePoolSize - Val;
586 | FCorePoolSize := Val;
587 | if (LExtra < 0) then begin
588 | LSize := FWorkQueue.Count;
589 | Inc(LExtra);
590 | Dec(LSize);
591 | while (LExtra < 0) and (LSize > 0) and (FPoolSize < val) do begin
592 | LThread := AddThread(nil);
593 | if not Assigned(LThread) then begin
594 | LThread.Resume();
595 | end else begin
596 | Break;
597 | end;
598 | Inc(LExtra);
599 | Dec(LSize);
600 | end;
601 | end else if (LExtra > 0) and (FPoolSize > val) then begin
602 | LIx := 0;
603 | Dec(LExtra);
604 | while (LIx < FWorkers.Count) and (LExtra > 0) and (FPoolSize > Val)
605 | and (FWorkQueue.RemainingCapacity = 0) do begin
606 | (FWorkers[Lix] as TWorker).InterruptIfIdle();
607 | Dec(LExtra);
608 | end;
609 | end;
610 | finally
611 | FLock.Release();
612 | end;
613 | end;
614 |
615 | procedure TThreadPoolExecutor.SetKeepAliveTime(val: Integer);
616 | begin
617 | if (val < 0) then raise EIllegalArgument.Create();
618 | if (val = 0) and AllowsCoreThreadTimeOut then raise ECoreThreadNonZeroKeepAliveTime.Create();
619 | FKeepAliveTime := val;
620 | end;
621 |
622 | procedure TThreadPoolExecutor.SetMaximumPoolSize(val: Integer);
623 | var
624 | LExtra: Integer;
625 | LIx: Integer;
626 | begin
627 | if (val <= 0) or (val < FCorePoolSize) then raise EIllegalArgument.Create();
628 | FLock.Acquire();
629 | try
630 | LExtra := FMaximumPoolSize - val;
631 | FMaximumPoolSize := val;
632 | if (LExtra > 0) and (FPoolSize > val) then begin
633 | LIx := 0;
634 | while (LIx < FWorkers.Count) and (LExtra > 0) and (FPoolSize > Val)
635 | and (FWorkQueue.RemainingCapacity = 0) do begin
636 | (FWorkers[Lix] as TWorker).InterruptIfIdle();
637 | Dec(LExtra);
638 | end;
639 | end;
640 | finally
641 | FLock.Release();
642 | end;
643 | end;
644 |
645 | procedure TThreadPoolExecutor.SetRejectedExecutionHandler(
646 | const Value: IRejectedExecutionHandler);
647 | begin
648 | if not Assigned(Value) then raise ENullPointer.Create();
649 | FRejectedExecutionHandler := Value;
650 | end;
651 |
652 | procedure TThreadPoolExecutor.SetThreadPooledFactory(const Value: IThreadPooledFactory);
653 | begin
654 | if not Assigned(Value) then raise ENullPointer.Create;
655 | FThreadPooledFactory := Value;
656 | end;
657 |
658 | procedure TThreadPoolExecutor.Shutdown;
659 | var
660 | LFullyTerminated: Boolean;
661 | LState: Integer;
662 | LWorker: Pointer;
663 | begin
664 | LFullyTerminated := false;
665 | FLock.Acquire();
666 | try
667 | if (FWorkers.Count > 0) then begin
668 | LState := FRunState;
669 | if (LState = STATE_RUNNING) then FRunState := STATE_SHUTDOWN;
670 | try
671 | for LWorker in FWorkers do begin
672 | TWorker(LWorker).InterruptIfIdle;
673 | end;
674 | except
675 | on E: Exception do begin
676 | FRunState := LState;
677 | raise;
678 | end;
679 | end;
680 | end else begin
681 | LFullyTerminated := true;
682 | FRunState := STATE_TERMINATED;
683 | { TODO : Leave all lock.acquire }
684 | end;
685 | finally
686 | FLock.Release();
687 | end;
688 | if LFullyTerminated then Terminated;
689 | end;
690 |
691 | function TThreadPoolExecutor.ShutdownNow: TRunnableArray;
692 | var
693 | LFullyTerminated: Boolean;
694 | LState: Integer;
695 | LWorker: Pointer;
696 | LList: TInterfaceArray;
697 | I: Integer;
698 | begin
699 | SetLength(Result, 0);
700 | LFullyTerminated := false;
701 | FLock.Acquire();
702 | try
703 | if (FWorkers.Count > 0) then begin
704 | LState := FRunState;
705 | if (LState <> STATE_TERMINATED) then FRunState := STATE_STOP;
706 | try
707 | for LWorker in FWorkers do begin
708 | TWorker(LWorker).InterruptNow();
709 | end;
710 | except
711 | on E: Exception do begin
712 | FRunState := LState;
713 | raise;
714 | end;
715 | end;
716 | end else begin
717 | LFullyTerminated := true;
718 | FRunState := STATE_TERMINATED;
719 | { TODO : Leave all lock.acquire }
720 | end;
721 | finally
722 | FLock.Release();
723 | end;
724 | if LFullyTerminated then Terminated;
725 |
726 | LList := FWorkQueue.ToArray();
727 | SetLength(Result, Length(LList));
728 | for I := Low(LList) to High(LList) do begin
729 | Result[I] := IRunnable(LList[I]);
730 | end;
731 | end;
732 |
733 | procedure TThreadPoolExecutor.Terminated;
734 | begin
735 | { TODO : Implement }
736 | end;
737 |
738 | procedure TThreadPoolExecutor.WorkerDone(const AWorker: TWorker);
739 | var
740 | LState: Integer;
741 | LThread: TThread;
742 | begin
743 | FLock.Acquire();
744 | try
745 | FCompletedTaskCount := FCompletedTaskCount + AWorker.CompletedTasks;
746 | FWorkers.Remove(AWorker);
747 | Dec(FPoolSize);
748 | if (FPoolSize > 0) then Exit;
749 |
750 | LState := FRunState;
751 | Assert(LState <> STATE_TERMINATED, 'Unexpected state.');
752 |
753 | if (LState <> STATE_STOP) then begin
754 | if not FWorkQueue.IsEmpty then begin
755 | LThread := AddThread(nil);
756 | if Assigned(LThread) then begin
757 | LThread.Resume;
758 | Exit;
759 | end;
760 | end;
761 |
762 | if (LState = STATE_RUNNING) then Exit;
763 | end;
764 |
765 | //Leave all
766 | { TODO : Leave all lock.acquire }
767 | FRunState := STATE_TERMINATED;
768 | finally
769 | FLock.Release();
770 | end;
771 |
772 | Assert(FRunState = STATE_TERMINATED, 'Unexpected state');
773 |
774 | Terminated;
775 | end;
776 |
777 | { TDefaultThreadPooledFactory }
778 |
779 | constructor TDefaultThreadPooledFactory.Create;
780 | begin
781 | inherited;
782 | end;
783 |
784 | function TDefaultThreadPooledFactory.CreateThread(const AWorker: TWorker): TThreadPooled;
785 | begin
786 | Result := TThreadPooled.Create(AWorker);
787 | end;
788 |
789 | destructor TDefaultThreadPooledFactory.Destroy;
790 | begin
791 | inherited;
792 | end;
793 |
794 | { TWorker }
795 |
796 | constructor TWorker.Create(const AFirstTask: IRunnable);
797 | begin
798 | Create(nil, AFirstTask);
799 | end;
800 |
801 | constructor TWorker.Create(const AThreadPool: TThreadPoolExecutor;
802 | const AFirstTask: IRunnable);
803 | begin
804 | inherited Create();
805 | FThreadPool := AThreadPool;
806 | FFirstTask := AFirstTask;
807 | FLock := TCriticalSection.Create;
808 | FCompletedTasks := 0;
809 | FThread := nil;
810 | end;
811 |
812 | destructor TWorker.Destroy;
813 | begin
814 | FFirstTask := nil;
815 | FLock.Free;
816 | inherited;
817 | end;
818 |
819 | procedure TWorker.InterruptIfIdle;
820 | begin
821 | if FLock.TryEnter then begin
822 | try
823 | //If not locked, so there's no work being done
824 | FThread.Interrupt;
825 | finally
826 | FLock.Leave;
827 | end;
828 | end;
829 | end;
830 |
831 | procedure TWorker.InterruptNow;
832 | begin
833 | FThread.Interrupt;
834 | end;
835 |
836 | function TWorker.IsActive: boolean;
837 | begin
838 | Result := true;
839 | if FLock.TryEnter then begin
840 | FLock.Leave;
841 | Result := false;
842 | end;
843 | end;
844 |
845 | procedure TWorker.Run;
846 | var
847 | LTask: IRunnable;
848 | begin
849 | LTask := FFirstTask;
850 | try
851 | FFirstTask := nil;
852 | if not Assigned(LTask) then begin
853 | LTask := FThreadPool.GetTask();
854 | end;
855 | while (Assigned(LTask)) do begin
856 | RunTask(LTask);
857 | LTask := nil; //Helps garbage collector, preventing a non-destruction by core thread waiting forever
858 | LTask := FThreadPool.GetTask();
859 | end;
860 | finally
861 | FThreadPool.WorkerDone(Self);
862 | end;
863 | end;
864 |
865 | procedure TWorker.RunTask(const ATask: IRunnable);
866 | var
867 | LRan: Boolean;
868 | begin
869 | FLock.Acquire();
870 | try
871 | if (FThreadPool.FRunState <> TThreadPoolExecutor.STATE_STOP)
872 | and (FThread.Interrupted)
873 | and (FThreadPool.FRunState = TThreadPoolExecutor.STATE_STOP) then begin
874 | //It has been interrupted but never entered in special state to handle interruption
875 | FThread.Interrupt;
876 | SleepEx(1, true);
877 | end;
878 |
879 | LRan := false;
880 | FThreadPool.BeforeExecute(FThread, ATask);
881 | try
882 | ATask.Run;
883 | LRan := true;
884 | FThreadPool.AfterExecute(ATask, nil);
885 | Inc(FCompletedTasks);
886 | except
887 | on E: Exception do begin
888 | if not LRan then FThreadPool.AfterExecute(ATask, E);
889 | raise;
890 | end;
891 | end;
892 | finally
893 | FLock.Release();
894 | end;
895 | end;
896 |
897 | procedure TWorker.SetThread(const Value: TThreadPooled);
898 | begin
899 | FThread := Value;
900 | FThread.FreeOnTerminate := true;
901 | end;
902 |
903 | { TThreadPooled }
904 |
905 | constructor TThreadPooled.Create(const AWorker: TWorker);
906 | begin
907 | inherited Create(true);
908 | FWorker := AWorker;
909 | end;
910 |
911 | destructor TThreadPooled.Destroy;
912 | begin
913 | inherited;
914 | end;
915 |
916 | procedure TThreadPooled.DoHandleException;
917 | begin
918 | if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
919 | SysUtils.ShowException(FException, nil);
920 | end;
921 |
922 | procedure TThreadPooled.Execute;
923 | begin
924 | inherited;
925 | try
926 | FWorker.Run();
927 | except
928 | HandleException;
929 | end;
930 | end;
931 |
932 | procedure TThreadPooled.HandleException;
933 | begin
934 | FException := ExceptObject;
935 | try
936 | if (FException is EAbort) then Exit;
937 | Synchronize(DoHandleException);
938 | finally
939 | FException := nil;
940 | end;
941 | end;
942 |
943 | { TCallerRunsPolicy }
944 |
945 | procedure TCallerRunsPolicy.RejectedExecution(const ATask: IRunnable;
946 | const APool: TThreadPoolExecutor);
947 | begin
948 | if not APool.IsShutdown then ATask.Run();
949 | end;
950 |
951 | { TAbortPolicy }
952 |
953 | procedure TAbortPolicy.RejectedExecution(const ATask: IRunnable;
954 | const APool: TThreadPoolExecutor);
955 | begin
956 | raise ERejectecExecution.Create();
957 | end;
958 |
959 | { TDiscardPolicy }
960 |
961 | procedure TDiscardPolicy.RejectedExecution(const ATask: IRunnable;
962 | const APool: TThreadPoolExecutor);
963 | begin
964 | //
965 | end;
966 |
967 | { TDiscardOldestPolicy }
968 |
969 | procedure TDiscardOldestPolicy.RejectedExecution(const ATask: IRunnable;
970 | const APool: TThreadPoolExecutor);
971 | begin
972 | if not APool.IsShutdown then begin
973 | APool.Queue.Poll();
974 | APool.Execute(ATask);
975 | end;
976 | end;
977 |
978 | end.
979 |
--------------------------------------------------------------------------------
/Extensions/Source/Integrates/Pool/Threading.pas:
--------------------------------------------------------------------------------
1 | {*******************************************************}
2 | { }
3 | { ThreadPoolExecutor4Delphi }
4 | { }
5 | { Author: Lucas Moura Belo - LMBelo }
6 | { Date: 04/07/2019 }
7 | { Belo Horizonte - MG - Brazil }
8 | { }
9 | {*******************************************************}
10 |
11 | unit Threading;
12 |
13 | interface
14 |
15 | uses
16 | Classes, Contnrs, SyncObjs;
17 |
18 | type
19 | TThreadManager = class
20 | strict private
21 | class function GetInstance: TThreadManager; static;
22 | private
23 | class var FInstance: TThreadManager;
24 | private
25 | class procedure Initialize;
26 | class procedure Finalize;
27 | private
28 | FThreads: TStrings;
29 | FLock: TCriticalSection;
30 | public
31 | constructor Create;
32 | destructor Destroy; override;
33 |
34 | procedure AddThread(const AThread: TThread);
35 | procedure RemoveThread(const AThread: TThread);
36 | function GetThreadById(const AThreadId: cardinal): TThread;
37 |
38 | class function GetCurrentThread(): TThread;
39 |
40 | class property Instance: TThreadManager read GetInstance;
41 | end;
42 |
43 | TCustomThread = class(TThread)
44 | private
45 | FInterrupted: boolean;
46 | protected
47 | procedure HandleInterruption;
48 | public
49 | procedure AfterConstruction; override;
50 | procedure BeforeDestruction; override;
51 |
52 | procedure Interrupt;
53 | procedure Sleep(const AMilliseconds: cardinal);
54 |
55 | class procedure Yield;
56 | class function GetCurrentThread: TThread;
57 | class function GetCurrentThreadId: cardinal;
58 |
59 | property Interrupted: boolean read FInterrupted;
60 | end;
61 |
62 | implementation
63 |
64 | uses
65 | SysUtils, Windows, Exceptions;
66 |
67 | { TCustomThread }
68 |
69 | procedure TCustomThread.AfterConstruction;
70 | begin
71 | FInterrupted := false;
72 | TThreadManager.Instance.AddThread(Self);
73 | inherited;
74 | end;
75 |
76 | procedure TCustomThread.BeforeDestruction;
77 | begin
78 | TThreadManager.Instance.RemoveThread(Self);
79 | inherited;
80 | end;
81 |
82 | class function TCustomThread.GetCurrentThread: TThread;
83 | begin
84 | Result := TThreadManager.Instance.GetThreadById(GetCurrentThreadId);
85 | end;
86 |
87 | class function TCustomThread.GetCurrentThreadId: cardinal;
88 | begin
89 | Result := Windows.GetCurrentThreadId();
90 | end;
91 |
92 | procedure TCustomThread.HandleInterruption;
93 | procedure DoInterrupt();
94 | begin
95 | raise EInterrupted.Create();
96 | end;
97 | begin
98 | if FInterrupted then Exit;
99 | QueueUserAPC(Addr(DoInterrupt), Self.Handle, Cardinal(Self));
100 | FInterrupted := true;
101 | end;
102 |
103 | procedure TCustomThread.Interrupt;
104 | begin
105 | HandleInterruption;
106 | end;
107 |
108 | procedure TCustomThread.Sleep(const AMilliseconds: cardinal);
109 | begin
110 | FInterrupted := false;
111 | SleepEx(AMilliseconds, true);
112 | end;
113 |
114 | class procedure TCustomThread.Yield;
115 | begin
116 | Windows.Sleep(0);
117 | end;
118 |
119 | { TThreadManager }
120 |
121 | constructor TThreadManager.Create;
122 | begin
123 | FLock := TCriticalSection.Create;
124 | FThreads := TStringList.Create;
125 | end;
126 |
127 | destructor TThreadManager.Destroy;
128 | begin
129 | FThreads.Free;
130 | FLock.Free;
131 | inherited;
132 | end;
133 |
134 | class procedure TThreadManager.Finalize;
135 | begin
136 | FInstance.Free;
137 | end;
138 |
139 | class function TThreadManager.GetCurrentThread: TThread;
140 | begin
141 | Result := TThreadManager.Instance.GetThreadById(GetCurrentThreadId());
142 | end;
143 |
144 | class function TThreadManager.GetInstance: TThreadManager;
145 | begin
146 | if not Assigned(FInstance) then FInstance := TThreadManager.Create;
147 | Result := FInstance;
148 | end;
149 |
150 | procedure TThreadManager.AddThread(const AThread: TThread);
151 | begin
152 | FLock.Acquire;
153 | try
154 | FThreads.AddObject(IntToStr(AThread.ThreadID), AThread);
155 | finally
156 | FLock.Release;
157 | end;
158 | end;
159 |
160 | procedure TThreadManager.RemoveThread(const AThread: TThread);
161 | var
162 | LIx: Integer;
163 | begin
164 | FLock.Acquire;
165 | try
166 | LIx := FThreads.IndexOf(IntToStr(AThread.ThreadID));
167 | if LIx >= 0 then FThreads.Delete(LIx);
168 | finally
169 | FLock.Release;
170 | end;
171 | end;
172 |
173 | function TThreadManager.GetThreadById(const AThreadId: cardinal): TThread;
174 | var
175 | LCurThreadId: Cardinal;
176 | LIx: Integer;
177 | begin
178 | FLock.Acquire;
179 | try
180 | LCurThreadId := GetCurrentThreadId;
181 | LIx := FThreads.IndexOf(IntToStr(LCurThreadId));
182 | if LIx >= 0 then begin
183 | Result := FThreads.Objects[LIx] as TThread;
184 | end else begin
185 | Result := nil;
186 | end;
187 | finally
188 | FLock.Release;
189 | end;
190 | end;
191 |
192 | class procedure TThreadManager.Initialize;
193 | begin
194 | FInstance := nil;
195 | end;
196 |
197 | initialization
198 | TThreadManager.Initialize();
199 |
200 | finalization
201 | TThreadManager.Finalize();
202 |
203 | end.
204 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ThreadPoolExecutor4Delphi
2 | Java based ThreadPoolExecutor for Delphi
3 |
4 | Hi, Delphi community :)
5 |
6 | LMBelo here.
7 |
8 | I'd like to share my Java based ThreadPoolExecutor.
9 | It was firstly developed to execute asynchronous tasks and carry on them.
10 | It's on first steps and will get greater with your contribution.
11 |
12 | Should work on older Delphi versions xP
13 |
14 | See you.
15 |
--------------------------------------------------------------------------------