Multithreading 可连接std::thread的析构函数

Multithreading 可连接std::thread的析构函数,multithreading,c++11,g++,Multithreading,C++11,G++,规范(从CPP参考中获得)规定: ~thread();(从C++11开始) 销毁线程对象。如果*这仍然有一个关联的运行线程 (即joinable()==true),调用std::terminate() 我已经检查了在线程内部调用std::terminate()会中止整个程序 为了检查析构函数的行为,我编写了以下代码: #include <iostream> #include <thread> #include <memory> int main() {

规范(从CPP参考中获得)规定:

~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; 
}
#包括
#包括
#包括
int main(){
std::unique_ptr thread_ptr(新std::thread([])){

std::cout您可能是指
thread\u ptr.reset()
而不是
thread\u ptr.release()
release()
放弃指针的所有权,也就是说,您泄漏了
std::thread
实例,因此它的析构函数从未被调用。

发现得很好。有了这一更改,整个程序就会中止(至少会发出叮当声).
而(1){}
是UB BTW。