昶尊奚
昶尊奚

Reputation: 13

get segmentation fault when I try to use tbb to parallel my program

My program works fine in serial way, but get segmentation fault when I try to use tbb to parallelize it.

I'm a tbb green hand.My program is quiet simple but I can't figure out why it went wrong. I wish I could get some help here. Below is my program.

#include <iostream>
#include <opencv2/opencv.hpp>
#include <tbb/tbb.h>
using namespace std;
using namespace cv;
class test{
public:
    Mat * imgarr;
    test(){
        imgarr = new Mat[10];
        for(int i =0 ;i<10;i++){
            imgarr[i] = Mat::zeros(10,10,CV_64F);
        }
    }
    void add(int i) const {
        Mat& tmp = imgarr[i];
        tmp(Range(0,10),Range(0,10)) += 1;
    }
    void operator()(tbb::blocked_range<int>& r) const {
        for(int i = r.begin();i != r.end();i++){
            add(i);
        }
    }
    ~test(){
        delete[] imgarr;
    }

};
int main(){
    test a;
    tbb::parallel_for(tbb::blocked_range<int>(0,10), a);
    for(int i =0 ;i< 3;i++){
        cout << a.imgarr[0]<<endl;
    }
    return 0;
}

Upvotes: 1

Views: 528

Answers (1)

Alexey Kukanov
Alexey Kukanov

Reputation: 12784

tbb::parallel_for creates multiple copies of the supplied body object. Since you have not provided any copy constructor for class test, the default one will just copy the state, i.e. the imgarr pointer. Then, once a temporary test object created by TBB is destroyed, imgarr is released and you cannot work with it anymore.

Try using std::shared_ptr for imgarr.

Upvotes: 1

Related Questions