-
Notifications
You must be signed in to change notification settings - Fork 33
/
IOCompletionPortsThreadPool.pas
357 lines (291 loc) · 10.1 KB
/
IOCompletionPortsThreadPool.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2020, Michael R. . All rights reserved.
// ####
// #### Unless required by applicable law or agreed to in writing, software
// #### distributed under the License is distributed on an "AS IS" BASIS,
// #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// #### See the License for the specific language governing permissions and
// #### limitations under the License.
// ###################################################################
unit IOCompletionPortsThreadPool;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
// #####################################################
// #### Thread pool based on IO completion ports
// #####################################################
interface
{$IFDEF MSWINDOWS}
uses MtxThreadPool, SysUtils;
function CreateThreadPoolObj : IMtxThreadPool;
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
uses Classes,
{$IFDEF FPC} Windows
{$ELSE}
{$IF CompilerVersion >= 23.0} Winapi.Windows {$ELSE} Windows {$IFEND}
{$ENDIF}, SyncObjs, winCPUInfo, CPUFeatures, Contnrs;
type
TMtxIOCompletionThrdPool = class;
TTaskFinEvt = procedure( Sender : Pointer ) of Object;
TIOAsyncCall = record
fData : TObject;
fProc : TMtxProc;
fRec : Pointer;
fRecProc : TMtxRecProc;
fOnFinish : TTaskFinEvt;
FFatalErrorAddr : Pointer;
FFatalException : Exception;
public
procedure Execute;
procedure Create(proc : TMtxProc; obj : TObject; onFinish : TTaskFinEvt);
procedure CreateRec(proc : TMtxRecProc; rec : Pointer; onFinish : TTaskFinEvt);
end;
PIOAsyncCall = ^TIOAsyncCall;
{ TIOAsyncCallThread is a pooled thread. It looks itself for work. }
TIOAsyncCallThread = class(TThread)
protected
fPortHandle : THandle;
procedure Execute; override;
public
procedure ForceTerminate;
constructor Create(portHandle : THandle);
end;
TMtxIOCompletionThrdPool = class(TInterfacedObject, IMtxThreadPool)
private
fThreadList : TObjectList;
fMaxThreads: integer;
fNumThreads : integer;
fNumCPU : integer;
fPoolHdl : THandle;
public
procedure AddAsyncCall(call : PIOAsyncCall);
procedure InitPool( maxNumThreads : integer );
function CreateTaskGroup : IMtxAsyncCallGroup;
property MaxThreads : integer read fMaxThreads;
constructor Create;
destructor Destroy; override;
end;
type
TIOPortThreadGroup = class(TInterfacedObject, IMtxAsyncCallGroup)
private
fRefCntBuf : Array[0..7] of byte; // ensure 4 byte alignment on fRefCnt
fRefCnt : PInteger;
fCallIdx : integer;
fPool : TMtxIOCompletionThrdPool;
fTasks : Array[0..cMaxNumCores - 1] of TIOAsyncCall;
procedure OnFinish( Sender : Pointer ) ;
public
procedure AddTaskRec(proc : TMtxRecProc; rec : Pointer);
procedure AddTask(proc : TMtxProc; obj : TObject);
procedure SyncAll;
constructor Create(pool : TMtxIOCompletionThrdPool);
end;
{ TSimpleWinThreadGroup }
procedure TIOPortThreadGroup.AddTask(proc : TMtxProc; obj : TObject);
begin
InterlockedIncrement(fRefCnt^);
fTasks[fCallIdx].Create(proc, obj, OnFinish);
fPool.AddAsyncCall(@fTasks[fCallIdx]);
inc(fCallIdx);
end;
constructor TIOPortThreadGroup.Create(pool : TMtxIOCompletionThrdPool);
begin
fPool := pool;
fCallIdx := 0;
fRefCnt := PInteger( @fRefCntBuf[0] );
if (NativeUint(fRefCnt) and $03) <> 0 then
fRefCnt := PInteger( NativeUint(fRefCnt) + $04 - NativeUint(fRefCnt) and $3 );
inherited Create;
end;
procedure TIOPortThreadGroup.OnFinish(Sender: Pointer);
begin
PIOAsyncCall(Sender)^.fData.Free;
InterlockedDecrement( fRefCnt^ );
end;
procedure TIOPortThreadGroup.SyncAll;
var failObj : Exception;
failAddr : Pointer;
i : Integer;
begin
// ###########################################
// #### Just spin wait until all references vanish
while fRefCnt^ > 0 do
begin
TThread.SpinWait(100);
end;
failobj := nil;
failAddr := nil;
// ###########################################
// #### Check if one task failed
for i := 0 to fCallIdx - 1 do
begin
// only store one problem -> the others are freed
if fTasks[i].FFatalException <> nil then
begin
if failObj <> nil
then
// note: according to the help acqurieExceptionObject needs a
// call to ReleaseExceptionObject. But this function does nothing!
// TThread does also handle the excpetion like the way we do it here
// but frees the excpetion in the destructor (variable FFatalException) so
// we do it likewise.
fTasks[i].FFatalException.Free
else
begin
failObj := fTasks[i].FFatalException;
failAddr := fTasks[i].FFatalErrorAddr;
end;
end;
end;
// ###########################################
// #### Reraise if needed
if Assigned( failObj ) then
raise failObj at failAddr;
end;
procedure TIOPortThreadGroup.AddTaskRec(proc: TMtxRecProc; rec: Pointer);
begin
InterlockedIncrement(fRefCnt^);
ftasks[fCallIdx].CreateRec(proc, rec, OnFinish);
fPool.AddAsyncCall(@ftasks[fCallIdx]);
inc(fCallIdx);
end;
{ TIOAsyncCallThread }
const cShutdown = 0;
constructor TIOAsyncCallThread.Create(PortHandle : THandle);
begin
fPortHandle := PortHandle;
inherited Create(False);
end;
procedure TIOAsyncCallThread.Execute;
var bytesTransferred : DWORD;
CompletionKey : ULONG_PTR;
Overlapped: POverlapped;
Task : PIOAsyncCall;
finishedCalled : boolean;
begin
{$IFNDEF FPC}
NameThreadForDebugging('mrMath Worker Thread');
{$ENDIF}
while not Terminated do
begin
finishedCalled := True;
task := nil;
// perform two loops so we don't need to setup the exception record all the time
try
while not Terminated do
begin
// ###########################################
// #### Just wait for the next task
if not GetQueuedCompletionStatus(fPortHandle, BytesTransferred, CompletionKey, Overlapped, INFINITE) then
RaiseLastOSError;
finishedCalled := False;
// same as terminated flag
if CompletionKey = cShutdown then
exit;
Task := PIOAsyncCall(CompletionKey);
Task^.Execute;
// inform someone...
Task^.fOnFinish(Task);
finishedCalled := True;
end;
except
On E : Exception do
begin
if Assigned(Task) then
begin
Task^.FFatalException := Exception(AcquireExceptionObject);
Task^.FFatalErrorAddr := ExceptAddr;
if not finishedCalled then
Task^.fOnFinish(Task);
end;
end;
end;
end;
end;
procedure TIOAsyncCallThread.ForceTerminate;
begin
// send shutdown signal
PostQueuedCompletionStatus( fPortHandle, 0, cShutdown, nil );
end;
{ TMtxIOCompletionThrdPool }
procedure TMtxIOCompletionThrdPool.AddAsyncCall(call: PIOAsyncCall);
begin
if not PostQueuedCompletionStatus(fPoolHdl, 0, NativeUINT( call ), nil ) then
RaiseLastOSError;
end;
constructor TMtxIOCompletionThrdPool.Create;
begin
fThreadList := TObjectList.Create(True);
inherited Create;
end;
destructor TMtxIOCompletionThrdPool.Destroy;
var i : integer;
begin
for i := 0 to fThreadList.Count - 1 do
TIOAsyncCallThread(fThreadList[i]).ForceTerminate;
// wait for threads to finish...
fThreadList.Free;
// release resources
CloseHandle(fPoolHdl);
inherited;
end;
procedure TIOAsyncCall.Create(proc : TMtxProc; obj : TObject; onFinish : TTaskFinEvt);
begin
fOnFinish := onFinish;
fProc := proc;
fData := obj;
end;
procedure TIOAsyncCall.CreateRec(proc: TMtxRecProc; rec: Pointer; onFinish : TTaskFinEvt);
begin
fOnFinish := onFinish;
fRecProc := proc;
fRec := rec;
end;
procedure TIOAsyncCall.Execute;
begin
if Assigned(fRec)
then
fRecProc(fRec)
else
fProc(fData);
end;
procedure TMtxIOCompletionThrdPool.InitPool(maxNumThreads: integer);
var sysInfo : TSystemInfo;
i: Integer;
numAllocThreads : integer;
begin
fNumThreads := 0;
GetSystemInfo(sysInfo);
fMaxThreads := sysInfo.dwNumberOfProcessors;
if fMaxThreads > maxNumThreads then
fMaxThreads := maxNumThreads;
fNumCPU := sysInfo.dwNumberOfProcessors;
numAllocThreads := fNumCPU;
if fNumCPU > fMaxThreads then
numAllocThreads := fMaxThreads;
// ###########################################
// #### Create the port
fPoolHdl := CreateIoCompletionPort( INVALID_HANDLE_VALUE, 0, 0, numAllocThreads );
if fPoolHdl = 0 then
RaiseLastOSError;
// ###########################################
// #### Now allocate the given number of threads
for i := 0 to numAllocThreads - 1 do
fThreadList.Add( TIOAsyncCallThread.Create(fPoolHdl) );
end;
function TMtxIOCompletionThrdPool.CreateTaskGroup: IMtxAsyncCallGroup;
begin
Result := TIOPortThreadGroup.Create(self);
end;
function CreateThreadPoolObj : IMtxThreadPool;
begin
Result := TMtxIOCompletionThrdPool.Create;
end;
{$ENDIF}
end.