在多线程处理过程中,对象析构函数始终被调用,但对象并未超出范围

HAO LEE

我不确定为什么即使我调用了对象的成员函数,即使它仍在其作用域内,析构函数仍然被调用。一个简单的示例如下所示:

#include<thread>
#include<iostream>
class Obj1
{
private:

public:
    ~Obj1();
    void testFunc();
};

Obj1::~Obj1()
{
    std::cout<<"destory\n";
}
void Obj1::testFunc(){
    std::cout<<"testfun\n";
}
#include "Obj1.hpp"
#include <thread>
#include <chrono>
int main()
{
    using namespace std::chrono_literals;
    Obj1 obj1 = Obj1();
    for(int i=0;i<100;i++){
        std::thread th =  std::thread(&Obj1::testFunc,obj1);
        std::this_thread::sleep_for(1s);
        std::cout<<"we wait\n";
    }
}

当我尝试运行它时,我可以看到输出:

destory
testfun
destory
we wait
terminate called without an active exception
Aborted (core dumped)

我想知道为什么obj1在线程每次结束时都被销毁?ps 1s延迟的原因是因为这是在实时系统中使用的,主循环具有较低的频率,因此该任务将在下一个循环之前完成。

WhozCraig

代码中的两个最大问题:

  • 您正在为每次std::thread启动创建副本
  • 您不是在等待线程终止。

Astd::thread需要一个可调用的参数,如果需要,还需要一个适当的参数。在您的情况下,可调用对象是成员函数的指针,它需要一个对象实例或地址(std::thread将使用其中任何一个)。您是通过制作的副本来给予前者obj1如果意图是让所有线程访问同一对象,则应改为传递地址。

然后等待线程终止

代码(添加了消息传递以检测复制构造)

#include <iostream>
#include <vector>
#include <thread>

class Obj1
{
public:
    Obj1() { std::cout << "construct\n"; }
    Obj1(const Obj1&) { std::cout << "copy\n"; }
    ~Obj1() { std::cout << "destroy\n"; }

    void testFunc();
};

void Obj1::testFunc() {
    std::cout << "testfun\n";
}

int main()
{
    Obj1 obj1;

    std::vector<std::thread> threads;
    for (int i = 0; i < 10; ++i)
        threads.emplace_back(&Obj1::testFunc, &obj1); // <<== HERE

    for (auto& t : threads)
        t.join();
}

输出(可以有所不同)

construct
testfun
testfun
testfun
testfun
testfun
testfun
testfun
testfun
testfun
testfun
destroy

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章