windows 我必须在线程句柄上 CloseHandle() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3959473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:25:57  来源:igfitidea点击:

Must I CloseHandle() on a thread handle?

c++windowshandle

提问by valdo

_beginthreadex returns a handle to a thread:

_beginthreadex 返回线程的句柄:

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.

例如,如果您需要在诸如 TerminateThread(..) 之类的调用中引用线程,则可以使用此句柄。

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.

根据_beginthreadex的 MSDN 页面,_beginthreadex 不会总是返回有效的句柄 - 例如,它也可能在错误等时返回 -1L。

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?

当线程正常完成时,我是否必须在线程句柄上调用 CloseHandle,或者我可以将其值设置为 NULL / INVALID_HANDLE_VALUE?

回答by valdo

Agree with Nemanja Trifunovic.

同意 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.

作为一般规则:CloseHandle除非另有说明,否则每个 Win32 句柄都必须由 关闭。

回答by Nemanja Trifunovic

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.

您发布链接的 MSDN 页面上的代码示例包括对CloseHandle(). 将句柄的值设置为 NULL 不会减少内核对象的内部引用计数,而且几乎没有用。