多线程成员函数c ++

时间:2018-04-17 06:14:24

标签: c++ multithreading oop stl member-functions

所以我试图在"库中的两个矩阵对象之间多点线点积计算"我正在写作。这是感兴趣的代码

double mat_cont::dot_t( mat_cont & other, const int offset,  \
const int upper_lim)

{
    double local_sum = 0;   
    for (int i = offset; i < upper_lim+offset; ++i)
        local_sum+=(this->mat[i] + other.mat[i]);

    return local_sum;
}


double mat_cont::dot( mat_cont & other){

    future<double> threads[3];
    int part = (int)(dim * dim) / (int)4;

    double sum = 0;

    for (int i = 1; i < 4; ++i){
        threads[i-1] = 
            async (std::launch::async,&mat_cont::dot_t, 
                  other, part*i, (i+1)*part);
    }
    for(int i = 0; i < part; ++i)
        sum+=(this->mat[i] + other.mat[i]);

    for(int i = 1; i < 3; ++i)
        sum+=threads[i].get();
    return sum;
    }

并抛出此编译错误

error: no matching function for call to 'async'
             threads[i-1] = async (std::launch::async,&mat_cont::dot_t, other, part*i, (i+1)*part);
                            ^~~~~ 
/Applications/Xcode.app/Contents/Developer/
Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/future:2337:1: 
note: candidate template ignored: substitution failure [with _Fp = double (mat_cont::*)(mat_cont &, int, int), _Args =
  <mat_cont &, int, int>]: no type named 'type' in 'std::__1::__invoke_of<double (mat_cont::*)(mat_cont &, int, int), mat_cont, int, int>'async(launch __policy, _Fp&& __f, _Args&&... __args)

我想知道我是否可以多线程这部分,或者我是否需要将这两个对象传递给友元函数进行多线程处理。我现在一直试图调试这个2小时,任何提示?

2 个答案:

答案 0 :(得分:1)

dot_tmat_cont的成员函数,它有3个参数,所以async函数调用中有一个缺少的元素 - this指针应作为第三个传递呼叫的参数

threads[i-1] = async (std::launch::async,&mat_cont::dot_t, this, std::ref(other), part*i, (i+1)*part);

答案 1 :(得分:1)

mat_cont::dot_t是一个非静态成员函数,因此它需要一个this对象来处理。

最简单的处理方法是使用捕获this指针的lambda。然后你可以像在任何其他成员函数中一样调用dot_t

threads[i-1] = std::async(std::launch::async,
                          [this, i, part, &other]() {
                              return dot_t(other, part*i, (i+1)*part);
                          });

Live Example