规范(?-从cppreference获得)指出:
〜thread(); (自C ++ 11起)
销毁线程对象。如果*这仍然具有关联的运行线程(即joinable()== true),则调用std :: terminate()。
我检查过std::terminate()
在线程内部调用会中止整个程序。
因此,为了检查析构函数的行为,我编写了以下代码:
#include <iostream>
#include <thread>
#include <memory>
int main() {
std::unique_ptr<std::thread> thread_ptr(new std::thread([](){
std::cout << "Starting thread: " << std::endl;
while(1) {}
}));
while(!thread_ptr->joinable()){}
std::cout << thread_ptr->joinable() << std::endl;
thread_ptr.release();
std::cout << "Main is still alive!" << std::endl;
return 0;
}
期望中止整个过程。
没有发生这种情况,所有输出都是消息的排列,例如:
1启动线程:
主仍然活着!
我正在使用g ++:线程模型:posix,gcc版本4.8.1(Ubuntu 4.8.1-2ubuntu1〜12.04)
我对规格有误解吗?错误代码?还是g ++不仅符合该规范?
您可能thread_ptr.reset()
不是thread_ptr.release()
。release()
放弃指针的所有权,即,您泄漏std::thread
实例,因此永远不会调用其析构函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句