c++ - 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 地址并且它们是正确的。
解决方案
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”将重新分配。
推荐阅读
- javascript - 访问先前由另一个 html 文件填充的对象
- ios - iOS Swift5 将使用带锁的 NSMutableDictionary 而不是 var [:] 确保线程安全?
- node.js - 如何解决“找不到不同的支持对象”
- asp.net-core - 当覆盖率低于 dotnet 测试的目标时,Azure DevOps 构建不会失败
- java - 在 Android 的 CalendarView 中更新输入的日期
- javascript - 将页面滚动转换为内部 div 的滚动百分比
- r - 确定字符向量中与匹配向量 [R] 中的最大匹配数匹配的位置
- excel - 单元格值更改时更新下拉菜单 (Excel)
- python - 在 Bokeh 中单击按钮时根据 Radiobutton 和复选框的值采取行动
- spring - Spring Data JPA:不持久化父关系列映射