【问题标题】:multi-threading member functions c++多线程成员函数 C++
【发布时间】:2018-09-27 00:07:40
【问题描述】:

所以我正在尝试在我正在编写的“库”中对两个矩阵对象之间的点积计算进行多线程处理。这是感兴趣的代码

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 个小时,有什么提示吗?

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 作为三个参数中的“第一个”,而不是“第三个”
    • 我实际上尝试过,但它抛出了一个不同的错误,可悲的是。我认为它也可以这样工作
    • @MihaylA.A dot_tthis 指针上被调用,thisasync 调用的第三个参数,dot_t 的第一个参数是ref(other)
    • 我的意思是this 始终是第一个隐藏的参数。
    【解决方案2】:

    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

    【讨论】:

    • 顺便说一句,这最终奏效了。有趣的是,终于看到了 lambdas 的用例;还有其他 lambda 用例吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2023-01-10
    • 1970-01-01
    相关资源
    最近更新 更多