Search code examples
c++parallel-processingtbb

tbb::parallel_for passing ‘const value_type’ as ‘this’ argument discards qualifiers


Started learning TBB recently. I'm trying to implement compressed sparse row multiplication (datatype std::complex<int>) in parallel using TBB. Here is my code :

struct CSR {
    std::vector<std::complex<int>> values;
    std::vector<int> row_ptr={0};
    std::vector<int> cols_index;
    int rows;
    int cols;
    int NNZ;
};

std::vector<std::complex<int>> tbb_multiply(const CSR& A,
    const CSR& B) { // B here is transpose  
    
    std::vector<std::complex<int>> result(A.rows * B.rows, 0);
    tbb::parallel_for(0,A.rows,[=](int i){
        for (int j = A.row_ptr[i]; j < A.row_ptr[i + 1]; j++) {
            int Ai = A.cols_index[j];
            std::complex<int> Avalue = A.values[j];
            for (int k = 0; k < B.rows; k++) {
                std::complex < int > sum(0, 0);
                for (int l = B.row_ptr[k]; l < B.row_ptr[k + 1]; l++)
                    if (Ai == B.cols_index[l]) {
                        sum += Avalue * B.values[l];
                        break;
                    }
                if (sum != std::complex < int >(0, 0)) {
                    result[i * B.rows + k] = sum;
                }
            }
        }
    });
    return result;
}

When compiling it I get the next error :

error: passing ‘const value_type’ {aka ‘const std::complex’} as ‘this’ argument discards qualifiers [-fpermissive] result[i * B.rows + k] = sum;


Solution

  • You capture by-value which makes result const (since a lambda isn't mutable by default). Since you also aim to return result, I suggest that you capture by-reference instead:

    tbb::parallel_for(0, A.rows,[&](int i){
    //                           ^