Reputation: 2179
Let say I have three thread handles
HandleList[0] = hThread1;
HandleList[1] = hThread2;
HandleList[2] = hThread3;
/*All the above are of type HANDLE*/
Before closing the application, I want the thread to get its task done. So I want to make app wait till thread completes.
So I do,
WaitForMultipleObjects(3, HandleList, TRUE, INFINITE );
By this I'm able to make the thread, complete its task. But control never move to next line after the call to WaitForMultileObjects irrespective of all thread completing its task.
If I use, some seconds instead of INFINITE, it comes to next line after that many secs, irrspective of whether thread completes its task or not.
WaitForMultipleObjects(3, HandleList, TRUE, 10000 );
My problem here is, I'm can't go for seconds, as I may not be sure whether the threads will complete its task with the given time.
To list my problem in simple words, I want all my thread to finish the task, before I close my app. How can I achieve it using WaitForMultipleObjects API?
EDIT: As per MSDN..
dwMilliseconds [in] Time-out interval, in milliseconds.
Upvotes: 1
Views: 3809
Reputation: 391276
The simple answer is that you cannot achieve this with WaitForMultipleObjects.
The problem here is that the fault is not with this function, it's doing exactly what it is supposed to do, it waits for the threads to finish.
The problem here is that one or more of the threads never finish.
And that is the problem you need to solve. Why isn't the threads finishing?
Are they deadlocked? Are they running in a loop they aren't breaking out of?
Upvotes: 1
Reputation: 7189
You should signal all your threads to finish the job with SetEvent or by anything else. And be sure not to wait for itself.
Upvotes: 3
Reputation:
In your code you say:
WaitForMultipleObjects(3, HandleList, TRUE, INFINITE );
which will wait until all three threads have finished. Is this what you want? If you want to wait until any one of them is finished, you want:
WaitForMultipleObjects(3, HandleList, FALSE, INFINITE );
If the first version never returns, then it is because at least one of the threads never terminates. You might also want to look at the provisos on threads that create windows in the API docs at http://msdn.microsoft.com/en-us/library/ms687025%28VS.85%29.aspx.
Upvotes: 2