I create threads like this:
//...other none-relevant stuff
// First I make sure there is no thread already running in m_hThread, if there is, return (code not shown)
CWinThread* pThread = AfxBeginThread(ThreadFunc, (LPVOID*)pThreadData, THREAD_PRIORITY_LOWEST,
::DuplicateHandle (GetCurrentProcess (), pThread->m_hThread, GetCurrentProcess (), &m_hThread,
0, FALSE, DUPLICATE_SAME_ACCESS);
where m_hThread is a HANDLE member of CMyClass. Now, according to Jeff Prosise's "Programming Windows with MFC" book, if I take this route to create a thread, I need to explicitly call ::CloseHandle(), passing the HANDLE to my thread.
I don't currently do this.
The thing is, I don't create my thread in a GUI, so to speak. I have a standard class in a DLL that clients call. The thread posts messages to any client GUI, if they provide the thread with a HWND (it is all standard stuff). The only times I know that a thread is ended are
1) the client calls CMyClass::StopTask(), which stops the thread by setting an event that the thread periodically checks. StopTask() then waits on the thread handle m_hThread
// If we get to here, we know the thread has fully ended...
2) The function ThreadFunc() reaching the end.
So, I know I can call ::CloseHandle() after ::WaitForSingleObject(m_hThread, INFINITE) has completed, but where can I call it when the thread finishes naturally ? Could I call it at the end of ThreadFunc() ? ( To do this, I would need to pass m_hThread to ThreadFunc(). )
It is worth noting that this code does not fail, even when creating thread after thread all in the same HANDLE m_hThread. But still, I am not noticing any adverse effects from the absence of ::CloseHandle().
Why do I need to call it then ?