Re: Thread termination behavior
On Fri, 3 Apr 2009 10:50:01 -0700, BoHuang
<BoHuang@discussions.microsoft.com> wrote:
I have thread A created by CreateThread() and supplied a 'run' function
(lpStartAddress).
After the 'run' function returns 0, when can I be sure thread A is properly
terminated?
I ask because after the 'run' function terminates, thread A still lingers in
Visual Studio's debugger. Except now its call stack is deep in ntdll.dll,
hence I cannot examine what it is doing.
Thread A may or may not disappear soon from debugger window even as my main
thread continues executation.
I sometimes get error 170 (Resource in use) when calling wglMakeCurrent() in
the main thread, and I suspect the lingering thread A is the culprit.
Should I call CloseHandle() on thread A to close it immediately? If not,
what can I expect from the OS?
Closing a thread handle does not terminate the thread. However, until all
handles are closed, the OS does maintain some info about the thread, even
after the thread has terminated. When the process is exited, secondary
threads continue to run until they are forcibly terminated by the OS when
the process calls ExitProcess (the unbridled running while the process is
shutting down being a very bad thing to allow), and handles are closed.
As for detecting thread termination, a thread continues to run while its
handle remains non-signalled. Therefore, you need to use a wait function
such as WaitForSingleObject. You can also use GetThreadExitCode; if that
function returns STILL_ACTIVE, the thread is still running.
In an MFC program, you need to use CWinThread. See this page for some tips
on avoiding its design problems and info on "joining" with your secondary
threads:
http://members.cox.net/doug_web/threads.htm
Each question builds on the previous one, so the whole thing is relevant.
--
Doug Harrison
Visual C++ MVP