简体   繁体   English

使用C ++ 11 std :: thread native_handle以及我是否需要CloseHandle

[英]Using C++11 std::thread native_handle and whether I need to CloseHandle

I'm starting to get into the practice of using C++11 std::thread s. 我开始习惯使用C ++ 11 std::thread s。 Typically, with Win32, I need to call CloseHandle whenever I have a handle to a thread. 通常,使用Win32,每当我有一个线程CloseHandle时,我需要调用CloseHandle Do I still need to call CloseHandle when I use a C++11 native_handle ? 当我使用C ++ 11 native_handle时,我还需要调用CloseHandle吗? Also, if I don't use C++11 native handles, do thread handles get cleaned up properly? 另外,如果我不使用C ++ 11本机句柄,是否可以正确清理线程句柄?

Of course not. 当然不是。
Thread Objects has a destructor which releases any operating system specific resources that the object may acquired. Thread Objects有一个析构函数,它释放对象可能获取的任何特定于操作系统的资源。

Actually, every (good) C++ object has a destructor which cleans whatever is needed to be cleaned up and this destructor (when the code is written correctly) is called automatically by the program. 实际上,每一个(良好)C ++对象具有清洁任何需要被清理析构函数和此析构函数(当代码被正确地写入) 由程序自动调用。

this idiom is known as RAII - every object has a constructor which gathers resources that the object needs, and a peer destructor which releases them when the object gets out of scope. 这个习惯用法称为RAII - 每个对象都有一个构造函数,它收集对象所需的资源,以及一个对象析构函数,当对象超出范围时,它会释放它们。

when done correctly, this technique is far more powerfull than C-style manual resource management or a "high-level" garbage collector. 如果操作正确,这种技术比C风格的手动资源管理或“高级”垃圾收集器更强大。

as a word of advise, if the standard provides you with some utility, ignore completely the corresponding Win32 API. 作为建议,如果标准为您提供了一些实用程序,请完全忽略相应的Win32 API。 the standard does not depends on an operating system specific API to work correctly. 标准依赖于操作系统特定的API才能正常工作。

No, they are RAII, like shared pointers. 不,它们是RAII,就像共享指针一样。 Main thing you need to worry about are: 您需要担心的主要事项是:

  • synchronization (no pain no gain!) 同步(没有痛苦没有收获!)
  • that you cannot copy threads (deleted constructor) so you pass them by reference. 您无法复制线程(已删除的构造函数),因此您可以通过引用传递它们。

Details here. 细节在这里。

http://www.cplusplus.com/reference/thread/thread/thread/ http://www.cplusplus.com/reference/thread/thread/thread/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM