Anantha Subramaniam
Anantha Subramaniam

Reputation: 196

Wait Functions and CloseHandle Dependency

I settled down on using Wait Functions ( WaitForSingleObject,WaitForMultipleObject etc) for proper thread exit. In this case , the question is do i need to explicitly call CloseHandle ( Thread Handle ) to avoid memory leak or the wait function cleans up and closes the handle on its own? In case if CloseHandle needs to be explicitly called , will i be able to call "CreateThread ( same Thread Handle ) again? Will i be able to call GetExitCodeThread( ) again ?

NOTE : One StackOverFlow Question answers me the second part says i cannot call GetExitCode again , but it doesnt clarify whether missing to call out a CloseHandle after Wait function results in a Memory Leak or Not.

Upvotes: 1

Views: 4139

Answers (1)

Steve
Steve

Reputation: 7271

To avoid a memory leak you must call CloseHandle. Using functions such as GetExitCodeThread or WaitForSingleObject after a HANDLE has been closed causes undefined behaviour. It may work some of the time, but on other occasions it may crash or return a wrong answer. As explained in Sabotaging yourself: Closing a handle and then using it

While it's true that WaitForSingleObject returns WAIT_FAILED when given an invalid parameter, handle recycling means that any invalid handle can suddenly become valid again (but refer to an unrelated object).

For that reason, it is usually best to do:

CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;

This means that anything that tries to use the handle will fail with an appropriate error code.

Once you have cleaned up the handle properly, it is safe to then use it to create another thread.

handle = CreateThread(...);

It is now a handle that is assigned to your new thread and you can call GetExitCodeThread again until you do the final clean-up with CloseHandle.

Upvotes: 5

Related Questions