我试图编写一个类成员,该成员并行多次调用另一个类成员。

我写了一个简单的问题示例,甚至无法编译它。调用std::async怎么办?我想问题可能出在我如何传递函数上。

#include <vector>
#include <future>
using namespace std;
class A
{
    int a,b;
public:
    A(int i=1, int j=2){ a=i; b=j;}

    std::pair<int,int> do_rand_stf(int x,int y)
    {
        std::pair<int,int> ret(x+a,y+b);
        return ret;
    }

    void run()
    {
        std::vector<std::future<std::pair<int,int>>> ran;
        for(int i=0;i<2;i++)
        {
            for(int j=0;j<2;j++)
            {
                auto hand=async(launch::async,do_rand_stf,i,j);
                ran.push_back(hand);
            }
        }
        for(int i=0;i<ran.size();i++)
        {
            pair<int,int> ttt=ran[i].get();
            cout << ttt.first << ttt.second << endl;
        }
    }
};

int main()
{
    A a;
    a.run();
}

汇编:
g++ -std=c++11 -pthread main.cpp

最佳答案

do_rand_stf是一个非静态成员函数,因此如果没有类实例(隐式this参数)就无法调用。幸运的是,std::async处理其参数,例如std::bind,而bind可以使用std::mem_fn将成员函数指针变成一个函子,需要一个显式的this参数,因此您要做的就是将this传递给std::async调用,并在传递do_rand_stf时使用有效的成员函数指针语法:

auto hand=async(launch::async,&A::do_rand_stf,this,i,j);

但是,代码中还有其他问题。首先,使用std::coutstd::endl而不使用#include<iostream>。更严重的是,std::future是不可复制的,只能移动,因此,如果不使用push_back,就无法hand命名对象std::move。或者,只需将async结果直接传递给push_back即可:
ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));

关于c++ - C++中类成员的class和std::async,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11758414/

10-11 22:53
查看更多