9

I'm not interested in using the handle returned from _beginthreadex(). Is it safe to call CloseHandle() on it immediately?

I believe this must be done to avoid memory leaks.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
user1061590
  • 185
  • 2
  • 4
  • 1
    You need to eventually close the handle to avoid resource leak, but doing it immediately after starting the thread leaves you no option to be able to synchronize (wait) for thread completion using the handle. And yes, it is safe. – Roman R. Nov 23 '11 at 21:26
  • There is still another way to synchronize with the thread even if you immediately close the handle returned by _beginthreadex. The thread itself can access its thread id via GetCurrentThreadId and pass it to the main thread. Then you can always call OpenThread (with SYNCHRONIZE permission) to obtain a new handle from that thread id. – Jeff Wilhite Jul 09 '14 at 15:24

2 Answers2

10

Yes, you can close the handle as soon as you decide you no longer need that handle. That won't affect thread execution. However you likely should check whether the thread has been started at all before you proceed.

The leaks you're concerned about are not memory leaks, they are system resources leaks - usually they are much worse.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Thanks. What is the best way to determine is the newly created thread has actually started? – user1061590 Nov 23 '11 at 22:32
  • @user1061590: There isn't a "best" way, but I think you should check the value returned by `_beginthreadex()` to ensure that it succeeded. – sharptooth Nov 24 '11 at 06:16
-1

According to MSDN, you should not close the handle returned by __beginThreadEx: _endthread automatically closes the thread handle (whereas _endthreadex does not).Therefore, when using _beginthread and _endthread, do not explicitly close the thread handle by calling the Win32 CloseHandle API. (see http://msdn.microsoft.com/en-us/library/kdzttdcb(ar-sa).aspx for details.)

YoungLearner
  • 55
  • 2
  • 8
  • 2
    That part talks about a different function. "when using **_beginthread** and _endthread, do not explicitly close the thread handle` vs. "the handle returned by **_beginthreadex** has to be closed by the caller of _beginthreadex". – Baffe Boyois Nov 23 '11 at 18:24