5

_beginthreadex returns a handle to a thread:

m_hStreamStatsThread = (HANDLE) _beginthreadex( NULL, 0, StreamStatsThread, this, 0, NULL );

This handle may be used if you need to refer to the thread in calls like TerminateThread(..) for example.

According to the MSDN page on _beginthreadex, _beginthreadex won't always return a valid handle - e.g. it may also return -1L on error etc.

When a thread has completed normally, do I have to call CloseHandle on the thread handle, or can I just set its value to NULL / INVALID_HANDLE_VALUE?

2 Answers2

9

Agree with Nemanja Trifunovic.

Even after the thread exited - its handle is valid. You can for instance query its return value.

As a general rule: every Win32 handle must be closed by CloseHandle, unless otherwise specified.

valdo
  • 12,632
  • 2
  • 37
  • 67
  • 2
    Any Win32 *kernel* handle (i.e. anything that is of type `HANDLE`). For someone who works with WinAPI is obvious, but I've seen people trying to close windows/resource handles (`HWND`, `HICON`, ...) with `CloseHandle`. :) – Matteo Italia Oct 18 '10 at 18:23
  • 1
    Yes, you're right. The point is to close kernel handles. Those HWND, HICON, HCURSOR and etc. are user handles. – valdo Oct 18 '10 at 21:14
  • 1
    P.S. User handles - I meant - handles supported by user32. – valdo Oct 18 '10 at 21:16
3

The code sample on the MSDN page you posted a link to includes a call to CloseHandle(). Setting the handle's value to NULL does not decrease the kernel object's internal ref count and is pretty much useless anyway.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88