Re: Worker thread ending
On Sun, 20 Jan 2008 05:25:50 -0800 (PST), Newsgroupie <buzbymb@yahoo.co.uk>
wrote:
Hello,
I create a worker thread(s) which will usually run until I tell it to
stop, which I do by signalling a CEvent object which the thread will
see and drop out of the thread function.
However, sometimes the thread my drop out early because it has
completed its tasks or an error has occurred.
When I create this thread I retain a copy of its handle so that after
I have set the stop event I can pass the handle to
WaitForMultipleObject (along with several other thread handles) and
wait for the thread to complete (as it may spend some time tidying a
few things up between it being told to stop and it actually
finishing).
But when the thread finishes prematurely the handle is no longer valid
and so WaitForMultipleObject fails with a GetLastError of 6 (invalid
handle).
I always have the thread set to auto delete.
And that's the problem. You're allowing the thread to auto-delete, but you
merely copied the handle instead of using DuplicateHandle on it. (NB: Using
DuplicateHandle isn't the best way; see the web page I link to below for
more on that.)
The stop CEvent is not
deleted with the thread.
Can someone please suggest a better way for me to do this sort of
thing so that I can cleanly and safely detect that a running thread
has stopped and that previously running threads have also stopped.
Waiting on the thread handle is the only way to reliably tell if a thread
has completely stopped. (Well, there's also GetExitCodeThread, but it's
superfluous if you don't need the exit code, and it's subject to false
negatives for threads that are careless about their return codes.) You just
need to prevent the handle invalidation. For more on that, and in general
how to use CWinThread safely and deal with all these things, see:
http://members.cox.net/doug_web/threads.htm
I suppose what I really need to find out is if a thread handle is
still valid?
No. If you need to use a handle, you never allow it to become invalid. It's
as simple as that.
--
Doug Harrison
Visual C++ MVP