Utilizzo di TEvent e MsgWaitForMultipleObjects nel blocco del thread principale
Ho trovato il codice interessante di questo Remy. Delphi: come creare e utilizzare Thread localmente?
È possibile farlo in modo da poter eseguire più thread e attendere fino a quando non sono terminati tutti e quindi continuare con il thread principale? L'ho provato in questo modo ma senza successo ...
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;
Risposte
Può essere fatto in modo da poter eseguire più thread e attendere fino a quando non sono terminati tutti
Sì. Devi semplicemente creare più TEventoggetti, uno per ciascuno TThread, quindi memorizzare tutti i loro messaggi Handlein un array a cui passare MsgWaitForMultipleObjects():
procedure Requery(DataList: TStringList);
var
Events: array of TEvent;
H: array of THandle;
OpResult: array of Boolean;
i: Integer;
Ret, Count: DWORD;
// moved into a helper function so that the anonymous procedure
// can capture the correct Index...
procedure StartThread(Index: integer);
begin
Events[Index] := TEvent.Create;
TThread.CreateAnonymousThread(
procedure
begin
try
// run query in thread
OpResult[Index] := IsMyValueOK(DataList.Strings[Index]);
finally
Events[Index].SetEvent;
end;
end
).Start;
H[Index] := Events[Index].Handle;
end;
begin
if DataList.Count > 0 then
begin
SetLength(Events, DataList.Count);
SetLength(H, DataList.Count);
SetLength(OpResult, DataList.Count);
try
for i := 0 to DataList.Count-1 do begin
StartThread(i);
end;
Count := Length(H);
repeat
Ret := MsgWaitForMultipleObjects(Count, H[0], False, INFINITE, QS_ALLINPUT);
if Ret = WAIT_FAILED then RaiseLastOSError;
if Ret = (WAIT_OBJECT_0+Count) then
begin
Application.ProcessMessages;
Continue;
end;
for i := Integer(Ret-WAIT_OBJECT_0)+1 to High(H) do begin
H[i-1] := H[i];
end;
Dec(Count);
until Count = 0;
for i := Low(OpResult) to High(OpResult) do begin
Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i], True));
end;
finally
for i := Low(Events) to High(Events) do begin
Events[i].Free;
end;
end;
end;
// Do next jobs with query
...
end;
Detto questo, potresti in alternativa sbarazzarti degli TEventoggetti e aspettare TThread.Handleinvece gli s. Un thread Handleviene segnalato per un'operazione di attesa quando il thread è completamente terminato. L'unico trucco è che TThread.CreateAnonymousThread()crea una proprietà la TThreadcui FreeOnTerminateproprietà è True, quindi dovrai disattivarla manualmente:
procedure Requery(DataList: TStringList);
var
Threads: array of TThread;
H: array of THandle;
OpResult: array of Boolean;
i: Integer;
Ret, Count: DWORD;
// moved into a helper function so that the anonymous procedure
// can capture the correct Index...
procedure StartThread(Index: integer);
begin
Threads[Index] := TThread.CreateAnonymousThread(
procedure
begin
// run query in thread
OpResult[Index] := IsMyValueOK(DataList.Strings[Index]);
end
);
Threads[Index].FreeOnTerminate := False;
H[Index] := Threads[Index].Handle;
Threads[Index].Start;
end;
begin
try
SetLength(Threads, DataList.Count);
SetLength(H, DataList.Count);
SetLength(OpResult, DataList.Count);
for i := 0 to DataList.Count-1 do begin
StartThread(i);
end;
Count := Length(H);
repeat
Ret := MsgWaitForMultipleObjects(Count, H[0], False, INFINITE, QS_ALLINPUT);
if Ret = WAIT_FAILED then RaiseLastOSError;
if Ret = (WAIT_OBJECT_0+Count) then
begin
Application.ProcessMessages;
Continue;
end;
for i := Integer(Ret-WAIT_OBJECT_0)+1 to High(H) do begin
H[i-1] := H[i];
end;
Dec(Count);
until Count = 0;
for i := Low(OpResult) to High(OpResult) do begin
Memo1.Lines.Add('Value is: ' + BoolToStr(OpResult[i], True));
end;
finally
for i := Low(Threads) to High(Threads) do begin
Threads[i].Free;
end;
end;
// Do next jobs with query
...
end;
In ogni caso, si noti che MsgWaitForMultipleObjects()è limitato ad attendere un massimo di 63 ( MAXIMUM_WAIT_OBJECTS[64] - 1) handle alla volta. La WaitForMultipleObjects()documentazione spiega come aggirare tale limitazione, se è necessario:
Per attendere più di MAXIMUM_WAIT_OBJECTS handle, utilizza uno dei seguenti metodi:
- Crea un thread per attendere MAXIMUM_WAIT_OBJECTS handle, quindi attendi su quel thread più gli altri handle. Utilizza questa tecnica per suddividere le maniglie in gruppi di MAXIMUM_WAIT_OBJECTS.
- Chiama RegisterWaitForSingleObject per attendere su ogni handle. Un thread di attesa dal pool di thread attende MAXIMUM_WAIT_OBJECTS oggetti registrati e assegna un thread di lavoro dopo la segnalazione dell'oggetto o la scadenza dell'intervallo di timeout.
Oppure, potresti semplicemente elaborare il tuo elenco in lotti più piccoli, diciamo non più di 50-60 elementi alla volta.