对象析构函数在多线程处理时不断被调用,但该对象并未超出范围



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

#include<thread>
#include<iostream>
class Obj1
{
private:
public:
    ~Obj1();
    void testFunc();
};
Obj1::~Obj1()
{
    std::cout<<"destoryn";
}
void Obj1::testFunc(){
    std::cout<<"testfunn";
}
#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 waitn";
    }
}

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

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

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

代码中的两个最大问题:

  • 您正在为启动的每个std::thread制作副本。
  • 您不会等待线程终止。

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

然后等待线程终止,当然

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

#include <iostream>
#include <vector>
#include <thread>
class Obj1
{
public:
    Obj1() { std::cout << "constructn"; }
    Obj1(const Obj1&) { std::cout << "copyn"; }
    ~Obj1() { std::cout << "destroyn"; }
    void testFunc();
};
void Obj1::testFunc() {
    std::cout << "testfunn";
}
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

最新更新