gpt4 book ai didi

multithreading - 可连接 std::thread 的析构函数

转载 作者:行者123 更新时间:2023-12-01 03:47:14 30 4
gpt4 key购买 nike

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

~thread(); (since C++11)

Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.



我已经检查过电话 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;
}

期待中止整个过程。

没有发生这样的事情,所有输出都是消息的排列,例如:

1Starting thread:

Main is still alive!



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

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

最佳答案

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

关于multithreading - 可连接 std::thread 的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911734/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com