Search code examples
c++multithreadingc++11segmentation-faultstdthread

Getting segfault using c++11 std::thread


static T MultiplyElement(const Matrix& matrixA, const Matrix& matrixB, 
    unsigned M2col, unsigned M1row)
{
    T sumToReturn = 0;

    for (unsigned iM1colM2row = 0; iM1colM2row < matrixA.m_n; iM1colM2row++)
    {
        sumToReturn += 
            matrixA.m_data[M1row][iM1colM2row] * matrixB.m_data[iM1colM2row][M2col];
    }

    return sumToReturn;
}

...

    std::vector<std::thread> threads;
    for(unsigned i = 0; i < outM ; ++i)
    {
        for(unsigned j = 0; j < outN; ++j)
        {
            threads.push_back(std::thread([&]()
            {
                outMatrix.m_data[i][j] = MultiplyElement(matrixA, matrixB, i, j);
            }
            ));
        }
    }
    for(auto& thread : threads)
    {
        thread.join();
    }

Compiled with: clang++ -std=c++11 -stdlib=libc++ newFile.cpp

I'm getting a segfault in MultiplyElement... any idea why?


Solution

  • I think the problem is with your capture. You are using reference-capture for all variables. You should be capturing i and j by value. Try [&, i, j] for your capture clause.

    Edit: You can check the answer here. You have the same issue.