Re: help closing handle of thread
On Thu, 16 Jul 2009 09:24:05 -0400, "Jeova Almeida"
<jeovaalmeida@yahoo.com> wrote:
Hello,
My main thread is creating a work thread (using CreateThread API).
If I use (in the main thread)
WaitForSingleObject(hThread);
CloseHandle(hThread);
Everything is fine.
But I can't use WaitForSingleObject, since it will make my thread act
synchronously, so that the main thread will stop executing until the thread
finishes.
Question:
a) What happens if I don't close the handle of the thread? It is only the
resource the OS hold for it that is not freed?
Seems like maybe the thread's stack won't be freed as well? There are
surely some other smallish data structures associated with the handle that
won't be freed until the handle is closed.
b) How would I close the handle of the thread without waiting for it to
finish (WaitForSingleObject)? I don't know how long it will last.
Closing the thread handle does not affect the execution of the thread.
However, you should close the handle only after detecting the thread has
terminated with a function such as WaitForSingleObject. For more, see:
http://members.cox.net/doug_web/threads.htm
In particular, see Q2 and Q8. Q8 discusses how the thread can use
PostMessage to notify the main thread that it has exited, and how the main
thread can safely deal with this notification. Q2 discusses why the main
thread should ensure all secondary threads have exited before exiting
itself, and Q3/4 explain how to do it.
(in this particular project I don't use MFC, so I cannot use AfxBeginThread)
You should at least use _beginthreadex instead of CreateThread.
--
Doug Harrison
Visual C++ MVP