How terminate a thread while I using WaitForMultipleObjects
I have a secondary thead (TMyWaitFor
) on my application which executes a few worker threads (TFooThr
) and wait for the finalization of these threads using the WaitForMultipleObjects
function
this is the relevant code
const
nThreads=5;
//these arrays are declarated in the private section of the TMyWaitFor thread
tArr : Array[1..nThreads] of TFooThr;
hArr : Array[1..nThreads] of THandle;
procedure TMyWaitFor.Execute;
Var
i : Integer;
begin
for i:=1 to nT开发者_StackOverflow中文版hreads do
begin
tArr[i]:=TFooThr.Create(AValue);
hArr[i]:=tArr[i].Handle;
end;
WaitForMultipleObjects(nThreads, @hArr[0], True, INFINITE);
end;
All works ok , but now In some situations, I can't wait for the threads (TFooThr) and I need cancel the operation, so I need to stop (terminate) all the threads which I started in the TMyWaitFor.Execute
, so the quesion is How I can terminate all TFooThr threads started the Execute method of the TMyWaitFor thread?
As David suggested, call Terminated on the thread and change your code to check the terminated flag regularly:
procedure TMyWaitFor.Execute;
Var
i : Integer;
begin
for i:=1 to nThreads do
begin
tArr[i]:=TFooThr.Create(AValue);
hArr[i]:=tArr[i].Handle;
end;
while not Terminated do
//wait half a second
if WaitForMultipleObjects(nThreads, @hArr[0], True, 500) <> WAIT_TIMEOUT then
Break;
end;
Update 2011-08-03
David and Serg are correct I'm afraid and I am incorrect. In TFooThr.Execute you should be checking for Terminated. In the main thread of your application, you can call Terminate on all the TFooThr's to kill them, and as long as they are taking notice of the Terminated flag, then TMyWaitFor will fall through all by itself.
You should remove your acceptance of this answer.
N@
精彩评论