Debian Codegraph @

components/multithreadprocs/mtprocs.pas

raw
1 {
2 **********************************************************************
3 This file is part of the Free Pascal run time library.
4
5 See the file COPYING.FPC, included in this distribution,
6 for details about the license.
7 **********************************************************************
8
9 Unit for light weight threads.
10
11 Copyright (C) 2008 Mattias Gaertner [email protected]
12
13 Abstract:
14 Light weight threads.
15 This unit provides methods to easily run a procedure/method with several
16 threads at once.
17 }
18 unit MTProcs;
19
20 {$mode objfpc}{$H+}
21
22 {$inline on}
23 {$ModeSwitch nestedprocvars}
24
25 interface
26
27 uses
28 Classes, SysUtils, MTPCPU;
29
30 type
31 TProcThreadGroup = class;
32 TProcThreadPool = class;
33 TProcThread = class;
34
35 { TMultiThreadProcItem }
36
37 TMTPThreadState = (
38 mtptsNone,
39 mtptsActive,
40 mtptsWaitingForIndex,
41 mtptsWaitingFailed,
42 mtptsInactive,
43 mtptsTerminated
44 );
45
46 TMultiThreadProcItem = class
47 private
48 FGroup: TProcThreadGroup;
49 FIndex: PtrInt;
50 FThread: TProcThread;
51 FWaitingForIndexEnd: PtrInt;
52 FWaitingForIndexStart: PtrInt;
53 fWaitForPool: PRTLEvent;
54 FState: TMTPThreadState;
55 public
56 destructor Destroy; override;
57 function WaitForIndexRange(StartIndex, EndIndex: PtrInt): boolean;
58 function WaitForIndex(Index: PtrInt): boolean; inline;
59 procedure CalcBlock(Index, BlockSize, LoopLength: PtrInt;
60 out BlockStart, BlockEnd: PtrInt); inline;
61 property Index: PtrInt read FIndex;
62 property Group: TProcThreadGroup read FGroup;
63 property WaitingForIndexStart: PtrInt read FWaitingForIndexStart;
64 property WaitingForIndexEnd: PtrInt read FWaitingForIndexEnd;
65 property Thread: TProcThread read FThread;
66 end;
67
68 { TProcThread }
69
70 TMTPThreadList = (
71 mtptlPool,
72 mtptlGroup
73 );
74
75 TProcThread = class(TThread)
76 private
77 FItem: TMultiThreadProcItem;
78 FNext, FPrev: array[TMTPThreadList] of TProcThread;
79 procedure AddToList(var First: TProcThread; ListType: TMTPThreadList); inline;
80 procedure RemoveFromList(var First: TProcThread; ListType: TMTPThreadList); inline;
81 procedure Terminating(aPool: TProcThreadPool; E: Exception);
82 public
83 constructor Create;
84 destructor Destroy; override;
85 procedure Execute; override;
86 property Item: TMultiThreadProcItem read FItem;
87 end;
88
89 TMTMethod = procedure(Index: PtrInt; Data: Pointer;
90 Item: TMultiThreadProcItem) of object;
91 TMTProcedure = procedure(Index: PtrInt; Data: Pointer;
92 Item: TMultiThreadProcItem);
93 TMTNestedProcedure = procedure(Index: PtrInt; Data: Pointer;
94 Item: TMultiThreadProcItem) is nested;
95
96 { TProcThreadGroup
97 Each task creates a new group of threads.
98 A group can either need more threads or it has finished and waits for its
99 threads to end.
100 The thread that created the group is not in the list FFirstThread. }
101
102 TMTPGroupState = (
103 mtpgsNone,
104 mtpgsNeedThreads, // the groups waiting for more threads to help
105 mtpgsFinishing, // the groups waiting for its threads to finish
106 mtpgsException // there was an exception => close asap
107 );
108
109 TProcThreadGroup = class
110 private
111 FEndIndex: PtrInt;
112 FException: Exception;
113 FFirstRunningIndex: PtrInt;
114 FFirstThread: TProcThread;
115 FLastRunningIndex: PtrInt;
116 FMaxThreads: PtrInt;
117 FNext, FPrev: TProcThreadGroup;
118 FPool: TProcThreadPool;
119 FStarterItem: TMultiThreadProcItem;
120 FStartIndex: PtrInt;
121 FState: TMTPGroupState;
122 FTaskData: Pointer;
123 FTaskFrame: Pointer;
124 FTaskMethod: TMTMethod;
125 FTaskNested: TMTNestedProcedure;
126 FTaskProcedure: TMTProcedure;
127 FThreadCount: PtrInt;
128 procedure AddToList(var First: TProcThreadGroup; ListType: TMTPGroupState); inline;
129 procedure RemoveFromList(var First: TProcThreadGroup); inline;
130 function NeedMoreThreads: boolean; inline;
131 procedure IncreaseLastRunningIndex(Item: TMultiThreadProcItem);
132 procedure AddThread(AThread: TProcThread);
133 procedure RemoveThread(AThread: TProcThread); inline;
134 procedure Run(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem); inline;
135 procedure IndexComplete(Index: PtrInt);
136 procedure WakeThreadsWaitingForIndex;
137 function HasFinishedIndex(aStartIndex, aEndIndex: PtrInt): boolean;
138 procedure EnterExceptionState(E: Exception);
139 public
140 constructor Create;
141 destructor Destroy; override;
142 property Pool: TProcThreadPool read FPool;
143 property StartIndex: PtrInt read FStartIndex;
144 property EndIndex: PtrInt read FEndIndex;
145 property FirstRunningIndex: PtrInt read FFirstRunningIndex; // first started
146 property LastRunningIndex: PtrInt read FLastRunningIndex; // last started
147 property TaskData: Pointer read FTaskData;
148 property TaskMethod: TMTMethod read FTaskMethod;
149 property TaskNested: TMTNestedProcedure read FTaskNested;
150 property TaskProcedure: TMTProcedure read FTaskProcedure;
151 property TaskFrame: Pointer read FTaskFrame;
152 property MaxThreads: PtrInt read FMaxThreads;
153 property StarterItem: TMultiThreadProcItem read FStarterItem;
154 end;
155
156 { TLightWeightThreadPool
157 Group 0 are the inactive threads }
158
159 { TProcThreadPool }
160
161 TProcThreadPool = class
162 private
163 FMaxThreadCount: PtrInt;
164 FThreadCount: PtrInt;
165 FFirstInactiveThread: TProcThread;
166 FFirstActiveThread: TProcThread;
167 FFirstTerminatedThread: TProcThread;
168 FFirstGroupNeedThreads: TProcThreadGroup;
169 FFirstGroupFinishing: TProcThreadGroup;
170 FCritSection: TRTLCriticalSection;
171 FDestroying: boolean;
172 procedure SetMaxThreadCount(const AValue: PtrInt);
173 procedure CleanTerminatedThreads;
174 procedure DoParallelIntern(const AMethod: TMTMethod;
175 const AProc: TMTProcedure; const ANested: TMTNestedProcedure;
176 const AFrame: Pointer; StartIndex, EndIndex: PtrInt;
177 Data: Pointer = nil; MaxThreads: PtrInt = 0);
178 public
179 // for debugging only: the critical section is public:
180 procedure EnterPoolCriticalSection; inline;
181 procedure LeavePoolCriticalSection; inline;
182 public
183 constructor Create;
184 destructor Destroy; override;
185
186 procedure DoParallel(const AMethod: TMTMethod;
187 StartIndex, EndIndex: PtrInt;
188 Data: Pointer = nil; MaxThreads: PtrInt = 0); inline;
189 procedure DoParallel(const AProc: TMTProcedure;
190 StartIndex, EndIndex: PtrInt;
191 Data: Pointer = nil; MaxThreads: PtrInt = 0); inline;
192 procedure DoParallelNested(const ANested: TMTNestedProcedure;
193 StartIndex, EndIndex: PtrInt;
194 Data: Pointer = nil; MaxThreads: PtrInt = 0); inline;
195
196 // experimental
197 procedure DoParallelLocalProc(const LocalProc: Pointer;
198 StartIndex, EndIndex: PtrInt;
199 Data: Pointer = nil; MaxThreads: PtrInt = 0); // do not make this inline!
200
201 // utility functions for loops:
202 procedure CalcBlockSize(LoopLength: PtrInt;
203 out BlockCount, BlockSize: PtrInt; MinBlockSize: PtrInt = 0); inline;
204 public
205 property MaxThreadCount: PtrInt read FMaxThreadCount write SetMaxThreadCount;
206 property ThreadCount: PtrInt read FThreadCount;
207 end;
208
209 var
210 ProcThreadPool: TProcThreadPool = nil;
211
212 threadvar
213 CurrentThread: TThread; // TProcThread sets this, you can set this for your own TThreads descendants
214
215 implementation
216
217 { TMultiThreadProcItem }
218
219 destructor TMultiThreadProcItem.Destroy;
220 begin
221 if fWaitForPool<>nil then begin
222 RTLeventdestroy(fWaitForPool);
223 fWaitForPool:=nil;
224 end;
225 inherited Destroy;
226 end;
227
228 function TMultiThreadProcItem.WaitForIndexRange(
229 StartIndex, EndIndex: PtrInt): boolean;
230 var
231 aPool: TProcThreadPool;
232 begin
233 //WriteLn('TLightWeightThreadItem.WaitForIndexRange START Index='+IntToStr(Index)+' StartIndex='+IntToStr(StartIndex)+' EndIndex='+IntToStr(EndIndex));
234 if (EndIndex>=Index) then exit(false);
235 if EndIndex<StartIndex then exit(true);
236 if Group=nil then exit(true); // a single threaded group has no group object
237 // multi threaded group
238 aPool:=Group.Pool;
239 if aPool.FDestroying then exit(false); // no more wait allowed
240 aPool.EnterPoolCriticalSection;
241 try
242 if Group.FState=mtpgsException then begin
243 //WriteLn('TLightWeightThreadItem.WaitForIndexRange Index='+IntToStr(Index)+', Group closing because of error');
244 exit(false);
245 end;
246 if Group.HasFinishedIndex(StartIndex,EndIndex) then begin
247 //WriteLn('TLightWeightThreadItem.WaitForIndexRange Index='+IntToStr(Index)+', range already finished');
248 exit(true);
249 end;
250 FState:=mtptsWaitingForIndex;
251 FWaitingForIndexStart:=StartIndex;
252 FWaitingForIndexEnd:=EndIndex;
253 if fWaitForPool=nil then
254 fWaitForPool:=RTLEventCreate;
255 RTLeventResetEvent(fWaitForPool);
256 finally
257 aPool.LeavePoolCriticalSection;
258 end;
259 //WriteLn('TLightWeightThreadItem.WaitForIndexRange '+IntToStr(Index)+' waiting ... ');
260 RTLeventWaitFor(fWaitForPool);
261 Result:=FState=mtptsActive;
262 FState:=mtptsActive;
263 //WriteLn('TLightWeightThreadItem.WaitForIndexRange END '+IntToStr(Index));
264 end;
265
266 function TMultiThreadProcItem.WaitForIndex(Index: PtrInt): boolean; inline;
267 begin
268 Result:=WaitForIndexRange(Index,Index);
269 end;
270
271 procedure TMultiThreadProcItem.CalcBlock(Index, BlockSize, LoopLength: PtrInt;
272 out BlockStart, BlockEnd: PtrInt);
273 begin
274 BlockStart:=BlockSize*Index;
275 BlockEnd:=BlockStart+BlockSize;
276 if LoopLength<BlockEnd then BlockEnd:=LoopLength;
277 dec(BlockEnd);
278 end;
279
280 { TProcThread }
281
282 procedure TProcThread.AddToList(var First: TProcThread;
283 ListType: TMTPThreadList);
284 begin
285 FNext[ListType]:=First;
286 if FNext[ListType]<>nil then
287 FNext[ListType].FPrev[ListType]:=Self;
288 First:=Self;
289 end;
290
291 procedure TProcThread.RemoveFromList(var First: TProcThread;
292 ListType: TMTPThreadList);
293 begin
294 if First=Self then
295 First:=FNext[ListType];
296 if FNext[ListType]<>nil then
297 FNext[ListType].FPrev[ListType]:=FPrev[ListType];
298 if FPrev[ListType]<>nil then
299 FPrev[ListType].FNext[ListType]:=FNext[ListType];
300 FNext[ListType]:=nil;
301 FPrev[ListType]:=nil;
302 end;
303
304 procedure TProcThread.Terminating(aPool: TProcThreadPool;
305 E: Exception);
306 begin
307 aPool.EnterPoolCriticalSection;
308 try
309 // remove from group
310 if Item.FGroup<>nil then begin
311 // an exception occured
312 Item.FGroup.EnterExceptionState(E);
313 Item.FGroup.RemoveThread(Self);
314 Item.FGroup:=nil;
315 end;
316 // move to pool's terminated threads
317 case Item.FState of
318 mtptsActive: RemoveFromList(aPool.FFirstActiveThread,mtptlPool);
319 mtptsInactive: RemoveFromList(aPool.FFirstInactiveThread,mtptlPool);
320 end;
321 AddToList(aPool.FFirstTerminatedThread,mtptlPool);
322 Item.FState:=mtptsTerminated;
323 finally
324 aPool.LeavePoolCriticalSection;
325 end;
326 end;
327
328 constructor TProcThread.Create;
329 begin
330 inherited Create(true);
331 fItem:=TMultiThreadProcItem.Create;
332 fItem.fWaitForPool:=RTLEventCreate;
333 fItem.FThread:=Self;
334 end;
335
336 destructor TProcThread.Destroy;
337 begin
338 FreeAndNil(FItem);
339 inherited Destroy;
340 end;
341
342 procedure TProcThread.Execute;
343 var
344 aPool: TProcThreadPool;
345 Group: TProcThreadGroup;
346 ok: Boolean;
347 E: Exception;
348 begin
349 MTProcs.CurrentThread:=Self;
350 aPool:=Item.Group.Pool;
351 ok:=false;
352 try
353 repeat
354 // work
355 Group:=Item.Group;
356 Group.Run(Item.Index,Group.TaskData,Item);
357
358 aPool.EnterPoolCriticalSection;
359 try
360 Group.IndexComplete(Item.Index);
361
362 // find next work
363 if Group.LastRunningIndex<Group.EndIndex then begin
364 // next index of group
365 Group.IncreaseLastRunningIndex(Item);
366 end else begin
367 // remove from group
368 RemoveFromList(Group.FFirstThread,mtptlGroup);
369 dec(Group.FThreadCount);
370 Item.FGroup:=nil;
371 Group:=nil;
372 if aPool.FFirstGroupNeedThreads<>nil then begin
373 // add to new group
374 aPool.FFirstGroupNeedThreads.AddThread(Self);
375 Group:=Item.Group;
376 end else begin
377 // mark inactive
378 RemoveFromList(aPool.FFirstActiveThread,mtptlPool);
379 AddToList(aPool.FFirstInactiveThread,mtptlPool);
380 Item.FState:=mtptsInactive;
381 RTLeventResetEvent(Item.fWaitForPool);
382 end;
383 end;
384 finally
385 aPool.LeavePoolCriticalSection;
386 end;
387 // wait for new work
388 if Item.FState=mtptsInactive then
389 RTLeventWaitFor(Item.fWaitForPool);
390 until Item.Group=nil;
391 ok:=true;
392 except
393 // stop the exception and store it
394 E:=Exception(AcquireExceptionObject);
395 Terminating(aPool,E);
396 end;
397 if ok then
398 Terminating(aPool,nil);
399 end;
400
401 { TProcThreadGroup }
402
403 procedure TProcThreadGroup.AddToList(var First: TProcThreadGroup;
404 ListType: TMTPGroupState);
405 begin
406 FNext:=First;
407 if FNext<>nil then
408 FNext.FPrev:=Self;
409 First:=Self;
410 FState:=ListType;
411 end;
412
413 procedure TProcThreadGroup.RemoveFromList(
414 var First: TProcThreadGroup);
415 begin
416 if First=Self then
417 First:=FNext;
418 if FNext<>nil then
419 FNext.FPrev:=FPrev;
420 if FPrev<>nil then
421 FPrev.FNext:=FNext;
422 FNext:=nil;
423 FPrev:=nil;
424 FState:=mtpgsNone;
425 end;
426
427 function TProcThreadGroup.NeedMoreThreads: boolean;
428 begin
429 Result:=(FLastRunningIndex<FEndIndex) and (FThreadCount<FMaxThreads)
430 and (FState<>mtpgsException);
431 end;
432
433 procedure TProcThreadGroup.IncreaseLastRunningIndex(Item: TMultiThreadProcItem);
434 begin
435 inc(FLastRunningIndex);
436 Item.FIndex:=FLastRunningIndex;
437 if NeedMoreThreads then exit;
438 if FState=mtpgsNeedThreads then begin
439 RemoveFromList(Pool.FFirstGroupNeedThreads);
440 AddToList(Pool.FFirstGroupFinishing,mtpgsFinishing);
441 end;
442 end;
443
444 procedure TProcThreadGroup.AddThread(AThread: TProcThread);
445 begin
446 AThread.Item.FGroup:=Self;
447 AThread.AddToList(FFirstThread,mtptlGroup);
448 inc(FThreadCount);
449 IncreaseLastRunningIndex(AThread.Item);
450 end;
451
452 procedure TProcThreadGroup.RemoveThread(AThread: TProcThread);
453 begin
454 AThread.RemoveFromList(FFirstThread,mtptlGroup);
455 dec(FThreadCount);
456 end;
457
458 procedure TProcThreadGroup.Run(Index: PtrInt; Data: Pointer;
459 Item: TMultiThreadProcItem); inline;
460 begin
461 if Assigned(FTaskFrame) then
462 CallLocalProc(FTaskProcedure,FTaskFrame,Index,Data,Item)
463 else if Assigned(FTaskProcedure) then
464 FTaskProcedure(Index,Data,Item)
465 else if Assigned(FTaskNested) then
466 FTaskNested(Index,Data,Item)
467 else
468 FTaskMethod(Index,Data,Item);
469 end;
470
471 procedure TProcThreadGroup.IndexComplete(Index: PtrInt);
472 var
473 AThread: TProcThread;
474 NewFirstRunningThread: PtrInt;
475 begin
476 // update FirstRunningIndex
477 NewFirstRunningThread:=FStarterItem.Index;
478 AThread:=FFirstThread;
479 while AThread<>nil do begin
480 if (NewFirstRunningThread>aThread.Item.Index)
481 and (aThread.Item.Index<>Index) then
482 NewFirstRunningThread:=aThread.Item.Index;
483 aThread:=aThread.FNext[mtptlGroup];
484 end;
485 FFirstRunningIndex:=NewFirstRunningThread;
486 // wake up threads (Note: do this even if FFirstRunningIndex has not changed)
487 WakeThreadsWaitingForIndex;
488 end;
489
490 procedure TProcThreadGroup.WakeThreadsWaitingForIndex;
491 var
492 aThread: TProcThread;
493 begin
494 if FState<>mtpgsException then begin
495 // wake up waiting threads
496 aThread:=FFirstThread;
497 while aThread<>nil do begin
498 if (aThread.Item.FState=mtptsWaitingForIndex)
499 and HasFinishedIndex(aThread.Item.WaitingForIndexStart,
500 aThread.Item.WaitingForIndexEnd)
501 then begin
502 // wake up the thread
503 aThread.Item.FState:=mtptsActive;
504 RTLeventSetEvent(aThread.Item.fWaitForPool);
505 end;
506 aThread:=aThread.FNext[mtptlGroup];
507 end;
508 if (FStarterItem.FState=mtptsWaitingForIndex)
509 and HasFinishedIndex(FStarterItem.WaitingForIndexStart,FStarterItem.WaitingForIndexEnd)
510 then begin
511 // wake up the starter thread of this group
512 FStarterItem.FState:=mtptsActive;
513 RTLeventSetEvent(FStarterItem.fWaitForPool);
514 end;
515 end else begin
516 // end group: wake up waiting threads
517 aThread:=FFirstThread;
518 while aThread<>nil do begin
519 if (aThread.Item.FState=mtptsWaitingForIndex)
520 then begin
521 // end group: wake up the thread
522 aThread.Item.FState:=mtptsWaitingFailed;
523 RTLeventSetEvent(aThread.Item.fWaitForPool);
524 end;
525 aThread:=aThread.FNext[mtptlGroup];
526 end;
527 if (FStarterItem.FState=mtptsWaitingForIndex)
528 then begin
529 // end group: wake up the starter thread of this group
530 FStarterItem.FState:=mtptsWaitingFailed;
531 RTLeventSetEvent(FStarterItem.fWaitForPool);
532 end;
533 end;
534 end;
535
536 function TProcThreadGroup.HasFinishedIndex(
537 aStartIndex, aEndIndex: PtrInt): boolean;
538 var
539 AThread: TProcThread;
540 begin
541 // test the finished range
542 if FFirstRunningIndex>aEndIndex then exit(true);
543 // test the unfinished range
544 if FLastRunningIndex<aEndIndex then exit(false);
545 // test the active range
546 AThread:=FFirstThread;
547 while AThread<>nil do begin
548 if (AThread.Item.Index>=aStartIndex)
549 and (AThread.Item.Index<=aEndIndex) then
550 exit(false);
551 AThread:=AThread.FNext[mtptlGroup];
552 end;
553 if (FStarterItem.Index>=aStartIndex)
554 and (FStarterItem.Index<=aEndIndex) then
555 exit(false);
556 Result:=true;
557 end;
558
559 procedure TProcThreadGroup.EnterExceptionState(E: Exception);
560 begin
561 if FState=mtpgsException then exit;
562 case FState of
563 mtpgsFinishing: RemoveFromList(Pool.FFirstGroupFinishing);
564 mtpgsNeedThreads: RemoveFromList(Pool.FFirstGroupNeedThreads);
565 end;
566 FState:=mtpgsException;
567 FException:=E;
568 WakeThreadsWaitingForIndex;
569 end;
570
571 constructor TProcThreadGroup.Create;
572 begin
573 FStarterItem:=TMultiThreadProcItem.Create;
574 FStarterItem.FGroup:=Self;
575 end;
576
577 destructor TProcThreadGroup.Destroy;
578 begin
579 FreeAndNil(FStarterItem);
580 inherited Destroy;
581 end;
582
583 { TProcThreadPool }
584
585 procedure TProcThreadPool.SetMaxThreadCount(const AValue: PtrInt);
586 begin
587 if FMaxThreadCount=AValue then exit;
588 if AValue<1 then raise Exception.Create('TLightWeightThreadPool.SetMaxThreadCount');
589 FMaxThreadCount:=AValue;
590 end;
591
592 procedure TProcThreadPool.CleanTerminatedThreads;
593 var
594 AThread: TProcThread;
595 begin
596 while FFirstTerminatedThread<>nil do begin
597 AThread:=FFirstTerminatedThread;
598 AThread.RemoveFromList(FFirstTerminatedThread,mtptlPool);
599 AThread.Free;
600 end;
601 end;
602
603 constructor TProcThreadPool.Create;
604 begin
605 FMaxThreadCount:=GetSystemThreadCount;
606 if FMaxThreadCount<1 then
607 FMaxThreadCount:=1;
608 InitCriticalSection(FCritSection);
609 end;
610
611 destructor TProcThreadPool.Destroy;
612
613 procedure WakeWaitingStarterItems(Group: TProcThreadGroup);
614 begin
615 while Group<>nil do begin
616 if Group.StarterItem.FState=mtptsWaitingForIndex then begin
617 Group.StarterItem.FState:=mtptsWaitingFailed;
618 RTLeventSetEvent(Group.StarterItem.fWaitForPool);
619 end;
620 Group:=Group.FNext;
621 end;
622 end;
623
624 var
625 AThread: TProcThread;
626 begin
627 FDestroying:=true;
628 // wake up all waiting threads
629 EnterPoolCriticalSection;
630 try
631 AThread:=FFirstActiveThread;
632 while AThread<>nil do begin
633 if aThread.Item.FState=mtptsWaitingForIndex then begin
634 aThread.Item.FState:=mtptsWaitingFailed;
635 RTLeventSetEvent(AThread.Item.fWaitForPool);
636 end;
637 AThread:=AThread.FNext[mtptlPool];
638 end;
639 WakeWaitingStarterItems(FFirstGroupNeedThreads);
640 WakeWaitingStarterItems(FFirstGroupFinishing);
641 finally
642 LeavePoolCriticalSection;
643 end;
644
645 // wait for all active threads to become inactive
646 while FFirstActiveThread<>nil do
647 Sleep(10);
648
649 // wake up all inactive threads (without new work they will terminate)
650 EnterPoolCriticalSection;
651 try
652 AThread:=FFirstInactiveThread;
653 while AThread<>nil do begin
654 RTLeventSetEvent(AThread.Item.fWaitForPool);
655 AThread:=AThread.FNext[mtptlPool];
656 end;
657 finally
658 LeavePoolCriticalSection;
659 end;
660
661 // wait for all threads to terminate
662 while FFirstInactiveThread<>nil do
663 Sleep(10);
664
665 // free threads
666 CleanTerminatedThreads;
667
668 DoneCriticalsection(FCritSection);
669 inherited Destroy;
670 end;
671
672 procedure TProcThreadPool.EnterPoolCriticalSection;
673 begin
674 EnterCriticalsection(FCritSection);
675 end;
676
677 procedure TProcThreadPool.LeavePoolCriticalSection;
678 begin
679 LeaveCriticalsection(FCritSection);
680 end;
681
682 procedure TProcThreadPool.DoParallel(const AMethod: TMTMethod;
683 StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt);
684 begin
685 if not Assigned(AMethod) then exit;
686 DoParallelIntern(AMethod,nil,nil,nil,StartIndex,EndIndex,Data,MaxThreads);
687 end;
688
689 procedure TProcThreadPool.DoParallel(const AProc: TMTProcedure;
690 StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt);
691 begin
692 if not Assigned(AProc) then exit;
693 DoParallelIntern(nil,AProc,nil,nil,StartIndex,EndIndex,Data,MaxThreads);
694 end;
695
696 procedure TProcThreadPool.DoParallelNested(const ANested: TMTNestedProcedure;
697 StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt);
698 begin
699 if not Assigned(ANested) then exit;
700 DoParallelIntern(nil,nil,ANested,nil,StartIndex,EndIndex,Data,MaxThreads);
701 end;
702
703 procedure TProcThreadPool.DoParallelLocalProc(const LocalProc: Pointer;
704 StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt);
705 var
706 Frame: Pointer;
707 begin
708 if not Assigned(LocalProc) then exit;
709 Frame:=get_caller_frame(get_frame);
710 DoParallelIntern(nil,TMTProcedure(LocalProc),nil,Frame,StartIndex,EndIndex,
711 Data,MaxThreads);
712 end;
713
714 procedure TProcThreadPool.CalcBlockSize(LoopLength: PtrInt; out BlockCount,
715 BlockSize: PtrInt; MinBlockSize: PtrInt);
716 begin
717 if LoopLength<=0 then begin
718 BlockCount:=0;
719 BlockSize:=1;
720 exit;
721 end;
722 // split work into equally sized blocks
723 BlockCount:=ProcThreadPool.MaxThreadCount;
724 BlockSize:=(LoopLength div BlockCount);
725 if (BlockSize<MinBlockSize) then BlockSize:=MinBlockSize;
726 if BlockSize<1 then BlockSize:=1;
727 BlockCount:=((LoopLength-1) div BlockSize)+1;
728 end;
729
730 procedure TProcThreadPool.DoParallelIntern(const AMethod: TMTMethod;
731 const AProc: TMTProcedure; const ANested: TMTNestedProcedure;
732 const AFrame: Pointer; StartIndex, EndIndex: PtrInt; Data: Pointer;
733 MaxThreads: PtrInt);
734 var
735 Group: TProcThreadGroup;
736 Index: PtrInt;
737 AThread: TProcThread;
738 NewThread: Boolean;
739 Item: TMultiThreadProcItem;
740 HelperThreadException: Exception;
741 begin
742 if (StartIndex>EndIndex) then exit; // nothing to do
743 if FDestroying then raise Exception.Create('Pool destroyed');
744
745 if (MaxThreads>MaxThreadCount) or (MaxThreads<=0) then
746 MaxThreads:=MaxThreadCount;
747 if (StartIndex=EndIndex) or (MaxThreads<=1) then begin
748 // single threaded
749 Item:=TMultiThreadProcItem.Create;
750 try
751 for Index:=StartIndex to EndIndex do begin
752 Item.FIndex:=Index;
753 if Assigned(AFrame) then
754 CallLocalProc(AProc,AFrame,Index,Data,Item)
755 else if Assigned(AProc) then
756 AProc(Index,Data,Item)
757 else if Assigned(AMethod) then
758 AMethod(Index,Data,Item)
759 else
760 ANested(Index,Data,Item);
761 end;
762 finally
763 Item.Free;
764 end;
765 exit;
766 end;
767
768 // create a new group
769 Group:=TProcThreadGroup.Create;
770 Group.FPool:=Self;
771 Group.FTaskData:=Data;
772 Group.FTaskMethod:=AMethod;
773 Group.FTaskProcedure:=AProc;
774 Group.FTaskNested:=ANested;
775 Group.FTaskFrame:=AFrame;
776 Group.FStartIndex:=StartIndex;
777 Group.FEndIndex:=EndIndex;
778 Group.FFirstRunningIndex:=StartIndex;
779 Group.FLastRunningIndex:=StartIndex;
780 Group.FMaxThreads:=MaxThreads;
781 Group.FThreadCount:=1;
782 Group.FStarterItem.FState:=mtptsActive;
783 Group.FStarterItem.FIndex:=StartIndex;
784 HelperThreadException:=nil;
785 try
786 // start threads
787 EnterPoolCriticalSection;
788 try
789 Group.AddToList(FFirstGroupNeedThreads,mtpgsNeedThreads);
790 while Group.NeedMoreThreads do begin
791 AThread:=FFirstInactiveThread;
792 NewThread:=false;
793 if AThread<>nil then begin
794 AThread.RemoveFromList(FFirstInactiveThread,mtptlPool);
795 end else if FThreadCount<FMaxThreadCount then begin
796 AThread:=TProcThread.Create;
797 if Assigned(AThread.FatalException) then
798 raise AThread.FatalException;
799 NewThread:=true;
800 inc(FThreadCount);
801 end else begin
802 break;
803 end;
804 // add to Group
805 Group.AddThread(AThread);
806 // start thread
807 AThread.AddToList(FFirstActiveThread,mtptlPool);
808 AThread.Item.FState:=mtptsActive;
809 if NewThread then
810 AThread.Start
811 else
812 RTLeventSetEvent(AThread.Item.fWaitForPool);
813 end;
814 finally
815 LeavePoolCriticalSection;
816 end;
817
818 // run until no more Index left
819 Index:=StartIndex;
820 repeat
821 Group.FStarterItem.FIndex:=Index;
822 Group.Run(Index,Data,Group.FStarterItem);
823
824 EnterPoolCriticalSection;
825 try
826 Group.IndexComplete(Index);
827 if (Group.FLastRunningIndex<Group.EndIndex) and (Group.FState<>mtpgsException)
828 then begin
829 inc(Group.FLastRunningIndex);
830 Index:=Group.FLastRunningIndex;
831 end else begin
832 Index:=StartIndex;
833 end;
834 finally
835 LeavePoolCriticalSection;
836 end;
837 until Index=StartIndex;
838 finally
839 // wait for Group to finish
840 if Group.FFirstThread<>nil then begin
841 EnterPoolCriticalSection;
842 try
843 Group.FStarterItem.FState:=mtptsInactive;
844 Group.FStarterItem.fIndex:=EndIndex;// needed for Group.HasFinishedIndex
845 // wake threads waiting for starter thread to finish
846 if Group.FStarterItem.FState<>mtptsInactive then
847 Group.EnterExceptionState(nil)
848 else
849 Group.WakeThreadsWaitingForIndex;
850 finally
851 LeavePoolCriticalSection;
852 end;
853 // waiting with exponential spin lock
854 Index:=0;
855 while Group.FFirstThread<>nil do begin
856 sleep(Index);
857 Index:=Index*2+1;
858 if Index>30 then Index:=30;
859 end;
860 end;
861 // remove group from pool
862 EnterPoolCriticalSection;
863 try
864 case Group.FState of
865 mtpgsNeedThreads: Group.RemoveFromList(FFirstGroupNeedThreads);
866 mtpgsFinishing: Group.RemoveFromList(FFirstGroupFinishing);
867 end;
868 finally
869 LeavePoolCriticalSection;
870 end;
871 HelperThreadException:=Group.FException;
872 Group.Free;
873 // free terminated threads (terminated, because of exceptions)
874 CleanTerminatedThreads;
875 end;
876 // if the exception occured in a helper thread raise it now
877 if HelperThreadException<>nil then
878 raise HelperThreadException;
879 end;
880
881 initialization
882 ProcThreadPool:=TProcThreadPool.Create;
883 CurrentThread:=nil;
884
885 finalization
886 ProcThreadPool.Free;
887 ProcThreadPool:=nil;
888
889 end.
890