我刚刚阅读了有关 C++11 中的 std::thread.detach()
的文档。
这是我的测试:
#include <iostream>
#include <thread>
#include <chrono>
static int counter = 0;
void func()
{
while (true) {
std::cout<<"running..."<<std::endl;
std::cout<<counter++<<std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
int main()
{
{
std::thread t(func);
t.detach();
} // t is released after this line
// t has died, so who is holding the resources of the detached thread???
std::cin.get();
return 0;
}
此代码按预期工作。所以看起来即使调用了它的析构函数,线程也可以继续运行。这是真的吗?
如果是真的,那么对象t被释放后,线程的资源到底是谁持有的呢?是否有某种机制来保存资源,例如隐藏的匿名对象?
最佳答案
在 C++ 中,std::thread
本身不管理执行线程。 C++ 根本没有管理执行线程的控件。
std::thread
管理线程句柄 - 线程的标识符(Posix 世界中的thread_t
,它主要是一个模型std::thread
)。这种标识符用于与线程通信(如在控制中),但在 C++ 中,唯一标准的通信方式是加入
线程(它只是在等待线程的完成)或 detach
ing 从它。
当 std::thread
析构函数被调用时,线程句柄也被析构,并且无法进一步控制线程。但是执行线程本身仍然存在并继续由实现(或者更准确地说,操作系统)管理。
请注意,对于非分离线程,如果线程尚未加入,std::thread
的析构函数将抛出异常。这只是一种保护措施,可防止开发人员在无意中意外丢失线程句柄。
关于c++ - 为什么即使调用了析构函数,C++11 中的分离线程也能执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62461870/