Re: WaitForSingleObject() failing?



On Fri, 06 Jan 2006 17:17:58 -0500, Joseph M. Newcomer
<newcomer@xxxxxxxxxxxx> wrote:

>How so? The way it works is that the last thing the thread does before returning from the
>thread is a PostMessage.

That may be the last thing you do, but it isn't the last thing
_AfxThreadEntry does, and that's the function MFC passed to _beginthreadex.
It is _AfxThreadEntry that calls your function, and when you return to it,
among other things, it goes on to call AfxEndThread, which normally causes
the CWinThread to do its evil "delete this." And those are just the
highlights.

There is yet another level of indirection in the CRT, where _beginthreadex
passes the address of a function _threadstartex to ::CreateThread, and it
is _threadstartex that ultimately calls _AfxThreadEntry:

_endthreadex (
( (unsigned (__CLR_OR_STD_CALL *)(void
*))(((_ptiddata)ptd)->_initaddr) )
( ((_ptiddata)ptd)->_initarg ) ) ;

In this case, _initaddr would be equal to _AfxThreadEntry. Note that
_endthreadex performs its own actions when control enters it, and even if
AfxEndThread didn't call _endthreadex for you, the CRT would call it for
you. So there is a lot that goes on in the thread after you perform your
PostMessage.

>Since nothing accesses the thread after that point, and it
>accesses nothing else, the only issue is whether or not the process completes and does
>ExitProcess before the thread actually finishes. As far as I can tell, all required
>conditions are met for clean thread termination.

Nope, the only way to achieve an orderly shutdown is to wait on the thread,
and this means keeping tabs on all your CWinThread objects, which means
disabling auto-delete and assuming ownership of them.

--
Doug Harrison
Visual C++ MVP
.