[英]C++ Threading with multidimensional vectors - access violation
我目前正在尝试在类的线程成员函数中完成工作。 因此,它将获得一个二维数组作为参数并将其填充到成员函数中。 这会重复多次。 产生第一个线程后,我立即收到读取或写入访问冲突错误。 我尝试了不同的方法来解决它,但无法使其正常工作。 虽然我发现这里几乎已经解决了所有问题,但是在这种情况下,我已经很长时间没有找到任何东西了。
void myClass::process(Vector3D& out_stack, long filterFaktor){
long rowSize = this->input2D.size();
long colSize = this->input2D.at(0).size();
int filterPerRowCount = ceil((double)rowSize / filterFaktor);
int filterPerColCount = ceil((double)colSize / filterFaktor);
std::vector<std::thread> threadPool;
//create new filter
long currentrow = 0;
while (currentrow < rowSize) {
long currentcol = 0;
while (currentcol < colSize) {
Filter* nextFilter = &this->createNextFilter(currentrow, currentcol, filterPerRowCount, filterPerColCount);
out_stack.push_back(Vector2D());
Vector2D* nptr = &out_stack[out_stack.size()-1];
//Here we are calling the thread which leads to the access violation
threadPool.push_back(std::thread(&myClass::nextProcess, this, nextFilter, nptr, rowSize, colSize));
currentcol += filterPerColCount;
}
currentrow += filterPerRowCount;
}
//wait until threads have finished
for (int iThread = 0; iThread < threadPool.size(); iThread++) {
threadPool[iThread].join();
}
}
void myClass::nextProcess(Filter* nextfilter, Vector2D* out_Map, long rowCount, long colCount){
//Loops this part -> creates the rows and pushes them in the out_Map
std::vector<double> nextRowInMap;
//... Calculates sum
nextRowInMap.push_back(sum);
//Push row in vector -> This is where the error occurs
out_Map->push_back(nextRowInMap);
}
typedef std::vector<double> Vector1D;
typedef std::vector<Vector1D> Vector2D;
typedef std::vector<Vector2D> Vector3D;
我想我只是缺少在C ++中使用Pointers的知识,因为我是新手。
在此先感谢您和最诚挚的问候
编辑
现在以这种方式尝试过,仍然无法正常工作:
out_stack.push_back(Vector2D());
long index = out_stack.size() - 1;
threadPool.push_back(std::thread(&myClass::nextProcess, this, nextFilter, &out_stack, index, rowSize, colSize));
在nextProcess中:
out_stack->at(index).push_back(nextRowInMap);
编辑
用mutex
解决。 另外,我需要通过过滤器而不是参考。
您的错误在这里:
out_stack.push_back(Vector2D());
Vector2D* nptr = &out_stack[out_stack.size()-1];
修改向量时,不能保证对象位于相同的地址。 当向量必须增长时,它可以在另一个地址上分配内部存储器,并将向量中的对象移动到新地址。 因此,指针可能在下一次push_back
无效
您应该将向量和索引传递给线程,并在每次需要时访问它
out_stack[index].push_back(...)
可能是在out_stack[index]
和push_back
之前,向量已被修改,并且您还在无效的内存上进行操作。 因此,您应该使用std::mutex
保护访问/修改向量。 我不确定最后一部分,但是是否有我不知道的线程安全保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.