Re: Is this ok?
Lisa Pearlson wrote:
Is it ok for a thread to close the handle to itself?
Yes.
DWORD g_hThread = NULL;
LONG ThreadFunc(LPVOID *pVoid)
{
// do stuff here
// self-delete
CloseHandle(g_hThread);
g_hThread = NULL;
}
g_hThread = CreateThread(...., ThreadFunc, ...);
No, this is not okay. Firstly, there is a distinction between a thread
handle and a thread's ID, though they can be mapped to each other.
CloseHandle() takes a handle, and a DWORD is not a handle. Please turn on
compiler warnings, it would have told you so. I also think that the
functions declaration for ThreadFunc() is not 100% correct, please fix this
now to keep your code portable in the future.
Secondly, there is a race-condition between invoking CreateThread() and
storing its returnvalue and its use inside the thread.
Thirdly, you must not access variables in different threads without suitable
synchronisation. This is multithreading basics and it also applies to
simple integers.
Lastly, the comment in your code is at the very least misleading. You
don't "self-delete" anything there. All you do is to release a handle to a
thread, the thread itself is independent thereof. I wonder what you want to
achieve with that.
If you don't need the thread's handle and want to let it run on its own in
the background, release the handle (after suitable error checking of
course) in the code that called CreateThread(). Simple as that, no race
conditions, no global variables, no problem.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Michael W??hrmann, Amtsgericht Hamburg HR B62 932