C ++线程和类方法。内存泄漏问题

我在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地址,它们是正确的。

dengfuji 回答:C ++线程和类方法。内存泄漏问题

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”将重新分配。

本文链接:https://www.f2er.com/3168540.html

大家都在问