C++ 中类成员上的类和 std::async
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11758414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class and std::async on class member in C++
提问by UldisK
I'm try to write a class member which calls another class member multiple times in parallel.
我正在尝试编写一个类成员,它并行地多次调用另一个类成员。
I wrote a simple example of the problem and can't even get to compile this. What am I doing wrong with calling std::async? I guess the problem would be with how I'm passing the the function.
我写了一个简单的问题示例,甚至无法编译它。我在调用 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();
}
compilation:
汇编:
g++ -std=c++11 -pthread main.cpp
回答by JohannesD
do_rand_stf
is a non-static member function and thus cannot be called without a class instance (the implicit this
parameter.) Luckily, std::async
handles its parameters like std::bind
, and bind
in turn can use std::mem_fn
to turn a member function pointer into a functor that takes an explicit this
parameter, so all you need to do is to pass this
to the std::async
invocation and use valid member function pointer syntax when passing the do_rand_stf
:
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);
There are other problems in the code, though. First off, you use std::cout
and std::endl
without #include
ing <iostream>
. More seriously, std::future
is not copyable, only movable, so you cannot push_back
the named object hand
without using std::move
. Alternatively, just pass the async
result to push_back
directly:
但是,代码中还有其他问题。首先,您使用std::cout
和std::endl
不使用#include
ing <iostream>
。更为严重的是,std::future
是不是可复制,只有移动的,所以你不能push_back
命名对象hand
,而无需使用std::move
。或者,只需将async
结果push_back
直接传递给:
ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));
回答by Andrew
You can pass the this
pointer to a new thread:
您可以将this
指针传递给新线程:
async([this]()
{
Function(this);
});