【问题标题】:C++ threads and class methods. Problem with memory leakageC++ 线程和类方法。内存泄漏问题
【发布时间】:2019-11-04 07:14:26
【问题描述】:

我在 C++ 中遇到线程问题,我想在不同的类对象上并行调用相同的方法。但是,程序遇到了一些问题。它有时会崩溃,有时会运行代码部分,但总是返回一个大得离谱的数字作为 ID,总是在 0 的位置。 类体:

class Gas{
public:
    Gas(const int id, const int imax, const int jmax){
        id_ = id;
        NX_ = imax;
        NR_ = jmax;
    }
private:
    int id_;                            //id of specimen
    int NX_;                            //quantity of elements in the X direction
    int NR_;                            //quantity of elements in the R direction

    std::vector<double> fr_;            //molar fraction
    std::vector<double> ms_;            //mass source
    std::vector<double> ms_old_;        //mass source value from previous iteration - for source relaxation
};

类方法:

double Gas::initialize(){
        int i, j, k;
        fr_.resize(NX_ * NR_);
        ms_.resize(NX_ * NR_);
        ms_old_.resize(NX_ * NR_);

        std::cout << "ID: " << id_ << '\n';


        k = 0;
        for(i = 0; i < NX_; i++){
            for(j = 0; j < NR_; j++){
                fr_[k] = 0.01;
                ms_[k] = 0.;
                k++;
            }
        }
    }

下面是代码中的线程实现:

std::vector<Gas> gases;
std::vector<Gas*> ptr_gas(6);
for(i = 0; i < 6; i++){                                     //creating vector holding objects representing specific gases
        gases.push_back(Gas(i, 10, 5));
        ptr_gas[i] = &gases[i];
    }

std::vector<std::thread*> th_gas;
int i = 0;
for(auto &X : ptr_gas){
    std::thread *thr = new std::thread(&Gas::initialize, ptr_gas[i]);
    th_gas.push_back(thr);
    i++;
}

for(auto &X : th_gas){
    X->join();
    delete X;
}
th_gas.clear();     

我放在方法中的 std::cout 的输出是这样的:

ID: ID: 1
4999616
ID: 5
ID: 4
ID: 2
ID: 3

看起来加入第一个创建的线程存在一些问题。有关如何避免该问题的任何建议?我已经检查了 ptr_gas 地址并且它们是正确的。

【问题讨论】:

  • 请显示minimal reproducible example,您的输出有什么问题?你期望它是什么?你认为initialise 中的互斥锁有什么作用?
  • Mutex 不做任何事情。我忘记在发布代码之前清除它
  • 如果这里的问题是打印的“无效”ID,则无法从您已经发布的代码中回答。这是Gas 实例或gas_ptr 向量(?)的构造中的一些问题,您的问题中不包含其代码。
  • 更新了代码,现在可以定义是什么问题了吗?
  • 这段代码不会通过我知道的任何代码审查过程。请检查所有内容...(例如,有一个循环范围并使用外部int i 计数器;您需要循环的范围是什么?)除此之外,您应该在需要时分配并使用智能指针.

标签: c++ multithreading class memory bad-alloc


【解决方案1】:
std::vector<Gas> gases;
std::vector<Gas*> ptr_gas(6);
for(i = 0; i < 6; i++){                                     //creating vector holding objects representing specific gases
        gases.push_back(Gas(i, grid));
        ptr_gas[i] = &gases[i];
    }

您在 ptr_gas 中的指针“无效”,因为当您 push_back 时“gases”将重新分配。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2011-09-27
    • 2020-08-08
    • 2011-05-16
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多