6

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?

E. Moffat
  • 3,165
  • 1
  • 21
  • 34
vico
  • 17,051
  • 45
  • 159
  • 315
  • Are you asking as a general case what happens when you omit `CloseHandle` or for the specific case of closing a handle returned from `_begintheadex`? – E. Moffat Sep 01 '15 at 17:14
  • I'm asking in general – vico Sep 01 '15 at 17:17
  • May I suggest implementing - e.g. for Debug config builds - _CRTDBG_MAP_ALLOC. You can get your software to tell you whether you've had a memory leak. It's always better to thoroughly clean up after yourself than to let the system do it on exit. – NoelC Sep 01 '15 at 17:19

5 Answers5

5

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.

Damon
  • 67,688
  • 20
  • 135
  • 185
  • I found opinion that not closing handles in some "magic" way can corrupt configuration file or database. So, seems, this is not truth. – vico Sep 02 '15 at 14:26
  • @vico: In a well-formed program, that should not happen (i.e. not be possible). But of course it's possible that you accidentially use a handle value that is a valid handle (which you haven't closed) in an erroneous program. Other than that, you can also lose data and get corrupt, half-written files if you do not close (or at least sync) C stdio handles and your process _terminates unexpectedly_. The reason is that your writes are buffered in user space, which goes kaboom once the process dies (similar could in theory happen with overlapped writes, but can't happen in practice due to design). – Damon Sep 02 '15 at 20:29
  • None of that can possibly happen with a thread handle, however. Also, none of that should be possible with a Windows file handle (writes either succeed or fail, and once they succeeded, the responsibility is with the OS). – Damon Sep 02 '15 at 20:31
1

Here you have a topic that response your question: Can I call CloseHandle() immediately after _beginthreadex() succeeded?

Greetings.

Community
  • 1
  • 1
Iván Portilla
  • 461
  • 1
  • 3
  • 13
1

Yes, you need to close the handle at some point, otherwise you will be leaking a finite OS resource.

wilx
  • 17,697
  • 6
  • 59
  • 114
0

May I suggest creating an RAII wrapper for your handles? Basically you write a wrapper that stores the handle you created and calls CloseHandle in its destructor. That way you never have to worry about remembering to close it (it will automatically close when it goes out of scope) or leaking a handle if an exception happens between opening the handle and closing it.

John
  • 31
  • 3
0

If you don't close the handle, then it will remain open until your process terminates. Depending on what's behind the handle, this can be bad. Resources are often associated to handles and these won't be cleaned up until your program terminates; if you only use a few handles and these happen to be 'lightweight' then it doesn't really matter. Other handles, such as file handles, have other side-effects to keeping the handle opened, for instance locking an opened file until your process exits. This can be very annoying to the user or other applications.

In general, it's best to clean-up all handles, but at the end of the process, all handles are closed by Windows.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53