使用线程编程时出现std::thread::_Invoker错误

3

编辑: 我正在尝试学习如何在C++中使用线程。我的代码出现问题,它给了我以下错误:

no matching function for call to 'std::thread::_Invoker<std::tuple<void (matrix_product<int, 0, 0>::*)(matrix_wrap<int>&, int, const matrix_wrap<int>&, const matrix_wrap<int>&), matrix_wrap<int>, int, matrix_wrap<int>, matrix_wrap<int> > >::_M_invoke(std::thread::_Invoker<std::tuple<void (matrix_product<int, 0, 0>::*)(matrix_wrap<int>&, int, const matrix_wrap<int>&, const matrix_wrap<int>&), matrix_wrap<int>, int, matrix_wrap<int>, matrix_wrap<int> > >::_Indices)'
  operator()()

这是使我出错的代码片段(在我编写此代码之前它是可以工作的):
void do_multiply_fico(matrix_wrap<T> result, matrix_wrap<T> lhs, matrix_wrap<T> rhs) {
        // Create an array of threads
        std::thread threads[lhs.get_height()];
        for (int i = 0; i < lhs.get_height(); ++i) {
            // Initialize each thread with the function responsible of multiplying only a part of the matrices
            threads[i] = std::thread(multiply_threading, result, i, lhs, rhs);
        }
        for (int i = 0; i < lhs.get_height(); ++i) {
            // Wait until each thead has finished
            threads[i].join();
        }
    }

    void multiply_threading(matrix_wrap<T>& result, const int thread_number, const matrix_wrap<T>& lhs, const matrix_wrap<T>& rhs){
        const unsigned height = result.get_height();
        const unsigned width = result.get_width();
        const unsigned span = lhs.get_width();
        assert(span==rhs.get_height());
        for (unsigned i=0; i!=height; ++i) {
            for (unsigned j = 0; j != width; ++j) {
                for (unsigned k = 0; k != span; ++k) {
                    result(i, j) += lhs(i, k) * rhs(k, j);
                }
            }
        }

    }

感谢您提前的帮助。

以下是关于IT技术的翻译:


那是完整的代码吗?你没有关闭两个for循环和最后一个函数。它有语法错误,无法运行。 - AmmoPT
现在循环已经关闭,但是它仍然给了我同样的错误。我发布的代码是导致我出错的部分。 - Doe
1个回答

2
看起来你正在尝试从一个成员函数构造std :: thread。那是行不通的:你需要一个实例来调用它。
而且,您还有一个更严重的问题,即默认情况下,引用参数将作为值类型传递给线程构造函数。您需要将它们包装在std :: ref中,以便编译并展示预期的行为。
不过,绕过所有这些的更简单的方法只是将lambda传递给std :: thread:
threads[i] = std::thread([this, &result, i, &lhs, &rhs](){
   multiply_threading(result, i, lhs, rhs);
});

这样参数的包装是通过lambda捕获来完成的,而不是通过std::thread的不确定性。 (参考捕获在某些情况下可能不安全,但由于您在同一函数中加入了所有内容,因此无需担心。)请注意,i被按值捕获,因为您将在后续迭代中更改其值,并且需要已创建的线程捕获创建它们时的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接