-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComputeCore.pas
More file actions
383 lines (319 loc) · 8.97 KB
/
Copy pathComputeCore.pas
File metadata and controls
383 lines (319 loc) · 8.97 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
unit ComputeCore;
interface
uses
System.SysUtils, System.Classes, System.SyncObjs,
Spring.Collections;
const
INFINITE = cardinal($FFFFFFFFF);
type
ITask = interface ['{CA107748-CA21-4570-9615-7CFBB837FCDA}']
function GetExceptObj: TObject;
function GetWorkDone: TEvent;
//
// Executes the task. Internal use only.
procedure Execute;
// Stores exception raised in the task (if any).
property ExceptObj: TObject read GetExceptObj;
// Signalled when the work is done.
property WorkDone: TEvent read GetWorkDone;
end;
IComputeCore = interface ['{FF061A68-2B81-40EB-A374-5C94CF13B610}']
// Schedules a procedure to be executed in a task as soon as possible.
function Run(const taskProc: TProc): ITask; overload;
// Waits for a task to complete execution
procedure WaitFor(const task: ITask);
end;
TTask = class
// Schedules a task in the global compute core
class function Run(const taskProc: TProc): ITask; static;
// Waits for a task running in the global compute core
class procedure WaitFor(const task: ITask); static;
end;
/// Implementation ///
TCCTask = class(TInterfacedObject, ITask)
strict private
FExceptObj: TObject;
FTaskProc: TProc;
FWorkDone: TEvent;
strict protected
function GetExceptObj: TObject;
function GetWorkDone: TEvent;
public
constructor Create(const taskProc: TProc);
destructor Destroy; override;
procedure Execute;
property ExceptObj: TObject read GetExceptObj;
property WorkDone: TEvent read GetWorkDone;
end;
TCCThread = class;
IComputeCoreEx = interface ['{2F143547-04AE-4994-B6D6-E691DF5EA384}']
function AllocateTask(thread: TCCThread; out task: ITask): boolean;
end;
TComputeCore = class;
TCCThread = class(TThread)
strict private
FIsActive: boolean;
FOwner_ref: TComputeCore;
FSignal: TEvent;
strict protected
procedure SetSignal(const value: TEvent);
protected
procedure TerminatedSet; {$IF CompilerVersion >= 23}override;{$ENDIF}
public
constructor Create(const owner_ref: TComputeCore); overload;
destructor Destroy; override;
{$IF CompilerVersion < 23}
procedure Terminate;
{$IFEND}
procedure Execute; override;
property IsActive: boolean read FIsActive write FIsActive;
property Signal: TEvent read FSignal write SetSignal;
end;
TComputeCore = class(TInterfacedObject, IComputeCore)
strict private
FInactiveThreads: TArray<TCCThread>;
FInactiveTop: integer;
FTasks: IQueue<ITask>;
FThreads: TArray<TCCThread>;
strict protected //internal inline functions
procedure __Acquire; inline;
procedure __Release; inline;
strict protected //thread-unsafe functions, must be called only when internal data is acquired
// Returns next task to be executed or 'nil' if there is no such task.
// Returns True when task is assigned.
function GetTask_U(var task: ITask): boolean;
// Marks a thread active/inactive
procedure MarkThreadActive_U(thread: TCCThread; isActive: boolean);
protected //thread-safe functions
// Atomically gets next task and sets the thread 'active' state
// (to True if the task was available, False if not).
// Returns True if the task was available.
// If the function returns False, 'task' is guaranteed to be 'nil'.
function AllocateTask(thread: TCCThread; out task: ITask): boolean;
// Atomically retrieves one inactive thread and marks it active.
// Returns False and 'nil' in the 'thread' parameter if there are no
// inactive threads.
function ActivateInactiveThread(var thread: TCCThread): boolean;
// Puts a task into the execution queue.
procedure QueueTask(const task: ITask);
public
constructor Create(numThreads: integer);
destructor Destroy; override;
function Run(const taskProc: TProc): ITask; overload;
procedure WaitFor(const task: ITask);
end;
var
GlobalComputeCore: IComputeCore;
implementation
{ TCCTask }
constructor TCCTask.Create(const taskProc: TProc);
begin
inherited Create;
FTaskProc := taskProc;
FWorkDone := TEvent.Create;
end;
destructor TCCTask.Destroy;
begin
FWorkDone.WaitFor(INFINITE);
FreeAndNil(FWorkDone);
inherited;
end;
procedure TCCTask.Execute;
begin
try
try
FTaskProc();
except
on E: Exception do
FExceptObj := AcquireExceptionObject;
end;
finally
FWorkDone.SetEvent;
end;
end;
function TCCTask.GetExceptObj: TObject;
begin
Result := FExceptObj;
end;
function TCCTask.GetWorkDone: TEvent;
begin
Result := FWorkDone;
end;
{ TCCThread }
constructor TCCThread.Create(const owner_ref: TComputeCore);
begin
inherited Create(false);
FOwner_ref := owner_ref;
FSignal := TEvent.Create(nil, false, false, '');
end;
destructor TCCThread.Destroy;
begin
FreeAndNil(FSignal);
inherited;
end;
procedure TCCThread.Execute;
var
task: ITask;
begin
NameThreadForDebugging('ComputeCore worker');
while (not Terminated) and (FSignal.WaitFor <> wrTimeout) do begin
while (not Terminated) and FOwner_ref.AllocateTask(Self, task) do
task.Execute;
end;
end;
procedure TCCThread.SetSignal(const value: TEvent);
begin
FSignal := Value;
end;
{$IF CompilerVersion < 23}
procedure TCCThread.Terminate;
begin
inherited Terminate;
TerminatedSet;
end;
{$IFEND}
procedure TCCThread.TerminatedSet;
begin
FSignal.SetEvent;
end;
{ TComputeCore }
procedure TComputeCore.__Acquire; //inline
begin
MonitorEnter(Self);
end;
procedure TComputeCore.__Release; //inline
begin
MonitorExit(Self);
end;
function TComputeCore.ActivateInactiveThread(var thread: TCCThread): boolean;
begin
__Acquire;
Result := FInactiveTop >= 0;
if Result then begin
thread := FInactiveThreads[FInactiveTop];
Dec(FInactiveTop);
MarkThreadActive_U(thread, true);
end
else
thread := nil;
__Release;
end;
function TComputeCore.AllocateTask(thread: TCCThread; out task: ITask): boolean;
begin
__Acquire;
MarkThreadActive_U(thread, GetTask_U(task));
__Release;
Result := assigned(task);
end;
constructor TComputeCore.Create(numThreads: integer);
var
iThread: integer;
thread: TCCThread;
begin
inherited Create;
Assert(numThreads > 0);
FTasks := TCollections.CreateQueue<ITask>;
SetLength(FInactiveThreads, numThreads);
SetLength(FThreads, numThreads);
for iThread := 1 to numThreads do begin
thread := TCCThread.Create(Self);
thread.IsActive := false;
FThreads[iThread-1] := thread;
FInactiveThreads[iThread-1] := thread;
end;
FInactiveTop := High(FInactiveThreads);
end;
destructor TComputeCore.Destroy;
var
thread: TCCThread;
begin
for thread in FThreads do
thread.Terminate;
for thread in FThreads do begin
thread.WaitFor;
FreeAndNil(thread);
end;
inherited;
end;
function TComputeCore.GetTask_U(var task: ITask): boolean;
begin
Result := FTasks.TryDequeue(task);
if not Result then
task := nil;
end;
procedure TComputeCore.MarkThreadActive_U(thread: TCCTHread; isActive: boolean);
var
iThread: integer;
begin
if isActive <> thread.IsActive then begin
thread.IsActive := isActive;
if isActive then begin
for iThread := 0 to FInactiveTop do
if FInactiveThreads[iThread] = thread then begin
if iThread <> FInactiveTop then
FInactiveThreads[iThread] := FInactiveThreads[FInactiveTop];
Dec(FInactiveTop);
break;
end;
end
else begin
Inc(FInactiveTop);
FInactiveThreads[FInactiveTop] := thread;
end;
end;
end;
procedure TComputeCore.QueueTask(const task: ITask);
begin
__Acquire;
FTasks.Enqueue(task);
__Release;
end;
function TComputeCore.Run(const taskProc: TProc): ITask;
var
thread: TCCThread;
begin
Result := TCCTask.Create(taskProc);
QueueTask(Result);
if ActivateInactiveThread(thread) then
thread.Signal.SetEvent;
end;
procedure TComputeCore.WaitFor(const task: ITask);
var
newTask: ITask;
begin
while task.WorkDone.WaitFor(0) = wrTimeout do begin
__Acquire;
GetTask_U(newTask);
__Release;
if not assigned(newTask) then
TThread.Yield
else begin
newTask.Execute;
if assigned(newTask.ExceptObj) then
raise Exception(newTask.ExceptObj);
end;
end;
if assigned(task.ExceptObj) then
raise Exception(task.ExceptObj);
end;
{ TTask }
class function TTask.Run(const taskProc: TProc): ITask;
var
interlockRes: pointer;
tmpCC : IComputeCore;
begin
if not assigned(GlobalComputeCore) then begin
Assert(NativeUInt(@GlobalComputeCore) mod SizeOf(pointer) = 0, 'TTask.Run: storage is not properly aligned!');
Assert(NativeUInt(@tmpCC) mod SizeOf(pointer) = 0, 'TTask.Run: tmpCC is not properly aligned!');
tmpCC := TComputeCore.Create(CPUCount - 1);
interlockRes := TInterlocked.CompareExchange(PPointer(@GlobalComputeCore)^, PPointer(@tmpCC)^, nil);
if interlockRes = nil then
PPointer(@tmpCC)^ := nil;
end;
Result := GlobalComputeCore.Run(taskProc);
end;
class procedure TTask.WaitFor(const task: ITask);
begin
GlobalComputeCore.WaitFor(task);
end;
end.