[英]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.