【问题标题】:Destructor of a joinable std::thread可连接 std::thread 的析构函数
【发布时间】:2014-11-12 17:44:11
【问题描述】:

规范(? - 从 cppreference 获得)指出:

~线程(); (C++11 起)

销毁线程对象。如果 *this 仍有关联的正在运行的线程 (即 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开始线程:

Main 还活着!

我正在使用 g++:线程模型:posix,gcc 版本 4.8.1(Ubuntu 4.8.1-2ubuntu1~12.04)

我对规范有错误的理解吗?错误的代码?还是 g++ 不仅仅符合这个规范?

【问题讨论】:

  • while(1) {} 是 UB BTW。

标签: multithreading c++11 g++


【解决方案1】:

您可能指的是thread_ptr.reset(),而不是thread_ptr.release()release() 放弃了指针的所有权,即您泄漏了 std::thread 实例,因此它的析构函数永远不会被调用。

【讨论】:

  • 很好看。随着这种变化,整个程序中止(至少在 Clang 中)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多