简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM