我试图编写一个类成员,该成员并行多次调用另一个类成员。
我写了一个简单的问题示例,甚至无法编译它。调用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::cout
和std::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/