【问题标题】:Object destructor kept being called when multithreading, yet the object is not out of scope多线程时不断调用对象析构函数,但对象没有超出范围
【发布时间】:2019-07-20 08:46:49
【问题描述】:

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

#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? p.s. 1s延迟的原因是因为这是在实时系统中使用的,主循环频率较低,任务将在下一个循环之前完成。

【问题讨论】:

  • 仅供参考。这是矫枉过正:Obj1 obj1 = Obj1(); 应该只是Obj1 obj1;。其次,线程参数是按值的(所以在你的情况下,复制)。如果要引用同一个对象,请使用 ref-wrapper。我会使用 obj1 的地址。
  • 你为什么要睡1s?让线程完成工作?不好的做法。你也不叫 th.join() 或 th.detach();
  • 您正在复制对象但您不知道它,因为您没有记录对 Big Five 的所有调用(仅是析构函数)。见stackoverflow.com/questions/56799469/…,这里是what happens when you fix the logging
  • @WhozCraig std::ref(obj1) ???
  • @HAOLEE for member fn ptrs,它将采用 obj 地址或绑定设置。前者在我下面的回答中。

标签: c++ multithreading oop c++11 c++14


【解决方案1】:

代码中的两个最大问题:

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

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

然后当然是等待线程终止

代码(添加了检测复制构造的消息)

#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

【讨论】:

猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
相关资源
最近更新 更多