I have found this Remy's interesting code. Delphi : How to create and use Thread locally?
Can this be done so I can do multiple threads and wait until they are all finished and then continue with main thread? I tried it like this but no success...
procedure Requery(DataList: TStringList);
var
Event: TEvent;
H: THandle;
OpResult: array of Boolean;
i: Integer;
begin
Event := TEvent.Create;
try
SetLength(OpResult, DataList.Count);
for i:=0 to DataList.Count-1 do begin
TThread.CreateAnonymousThread(
procedure
begin
try
// run query in thread
OpResult[i]:=IsMyValueOK(DataList.Strings[i]);
finally
Event.SetEvent;
end;
end
).Start;
H := Event.Handle;
end;
while MsgWaitForMultipleObjects(1, H, False, INFINITE, QS_ALLINPUT) = (WAIT_OBJECT_0+1) do Application.ProcessMessages;
for i:=Low(OpResult) to High(OpResult) do begin
Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i], True));
end;
finally
Event.Free;
end;
// Do next jobs with query
...
end;
Yes. You simply need to create multiple
TEvent
objects, one for eachTThread
, and then store all of theirHandle
s in an array to pass toMsgWaitForMultipleObjects()
:That being said, you could alternatively get rid of the
TEvent
objects and wait on theTThread.Handle
s instead. A thread'sHandle
is signaled for a wait operation when the thread is fully terminated. The only gotcha is thatTThread.CreateAnonymousThread()
creates aTThread
whoseFreeOnTerminate
property isTrue
, so you will have to turn that off manually:Either way, note that
MsgWaitForMultipleObjects()
is limited to waiting on a maximum of 63 (MAXIMUM_WAIT_OBJECTS
[64] - 1) handles at a time. TheWaitForMultipleObjects()
documentation explains how to work around that limitation, if you need to:Or, you could simply process your list in smaller batches, say no more than 50-60 items at a time.