Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call CloseHandle?

Tags:

c++

visual-c++

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?

like image 432
vico Avatar asked Sep 01 '15 17:09

vico


Video Answer


1 Answers

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.

like image 112
Damon Avatar answered Oct 11 '22 12:10

Damon