简体   繁体   English

多线程成员函数C ++

[英]multi-threading member functions c++

So I am trying to multithread the dot product computation between two matrix objects in a "library" I'm writing. 因此,我正在尝试在我正在编写的“库”中对两个矩阵对象之间的点积计算进行多线程处理。 here is the code of interest 这是感兴趣的代码

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;
    }

and this compilation error is thrown 并抛出此编译错误

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)

I'm wondering if I can multithread this part, or if I need to pass both of these objects into a friend function for multithreading. 我想知道我是否可以对该部分进行多线程处理,或者是否需要将这两个对象都传递给一个朋友函数进行多线程处理。 I've been trying to debug this for 2 hours now, any tips? 我已经尝试调试了2个小时,有什么提示吗?

dot_tdot_t的成员函数,它mat_cont 3个参数,因此async函数的调用中缺少一个元素- this指针应作为调用的第三个参数传递

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

mat_cont::dot_t is a non-static member function, so it needs a this object to work on. mat_cont::dot_t是一个非静态成员函数,因此需要this对象才能进行处理。

The easiest way to deal with that is to use a lambda that captures the this pointer. 处理该问题的最简单方法是使用捕获this指针的lambda。 Then you can call dot_t exactly like you would in any other member function: 然后,您可以像在其他任何成员函数中一样完全调用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 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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