2016-11-03 8 views
0

私は現在、自分のクラスのスレッドメンバー関数で作業をしようとしています。したがって、2次元配列をパラメータとして取得し、メンバ関数でそれを埋め込みます。これは複数回繰り返されます。最初のスレッドを生成した直後に、読み取りまたは書き込みアクセス違反でエラーが発生します。私はそれを解決するためにさまざまなアプローチを試みましたが、それを働かせることはできません。すでにここで解決された問題はほとんどありませんでしたが、この場合、私は今かなり長い間何かを見つけられませんでした。多次元ベクトルを使用したスレッディング - アクセス違反

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++でポインタを使用する知識が不足していると思うので、私はそれが初めてです。事前に

おかげ&宜しくは

EDIT

はまだ動作しません、今このようにそれを試してみました:

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); 

EDIT

解決済みmutexで解決しました。さらに、私は参照ではなくフィルターを渡す必要がありました。

答えて

0

あなたのエラーはここにある:

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でベクトルのアクセス/変更を保護する必要があります。私はその最後の部分では確信していませんが、私はそこにいくつかのスレッドの安全保証があるかどうかわかりません。

+0

3Dベクトル全体と作成された新しいインデックスを渡してみましたが、まだエラーが発生しました。たぶん私はミューテックスを試す必要があります。 – Nkr

関連する問題