I have code that creates a thread and closes it with CloseHandle
when the program finishes.
int main()
{
....
HANDLE hth1;
unsigned uiThread1ID;
hth1 = (HANDLE)_beginthreadex( NULL, // security
0, // stack size
ThreadX::ThreadStaticEntryPoint,
o1, // arg list
CREATE_SUSPENDED, // so we can later call ResumeThread()
&uiThread1ID );
....
CloseHandle( hth1 );
....
}
But why do I need to close the handle at all? What will happen if I will not do so?
But why do I need to close handle at all?
Handles are a limited resource that occupy both kernel and userspace memory. Keeping a handle alive not only takes an integer worth of storage, but also means that the kernel has to keep the thread information (such as user time, kernel time, thread ID, exit code) around, and it cannot recycle the thread ID since you might query it using that handle.
Therefore, it is best practice to close handles when they are no longer needed.
This is what you are to do per the API contract (but of course you can break that contract).
What will happens if I will not do so?
Well, to be honest... nothing. You will leak that handle, but for one handle the impact will not be measurable. When your process exits, Windows will close the handle.
Still, in the normal case, you should close handles that are not needed any more just like you would free memory that you have allocated (even though the operating system will release it as well when your process exits).
Although it may even be considered an "optimization" not to explicitly free resources, in order to have a correct program, this should always be done. Correctness first, optimization second.
Also, the sooner you release a resource (no matter how small it is) the sooner it is available again to the system for reuse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With