Class and std :: async on a member of a class in C ++

I am trying to write a member of a class that calls another member of the class several times.

I wrote a simple example of a problem and I can’t even compile it. What am I doing wrong with calling std :: async? I think the problem is with how I pass the function.

#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 
+22
c ++ c ++ 11
Aug 01 2018-12-12T00:
source share
2 answers

do_rand_stf is a non-static member function and therefore cannot be called without an instance of the class (implicit this parameter). Fortunately, std::async processes its parameters, such as std::bind , and bind in turn can use std::mem_fn to turn a pointer to a member function into a functor that takes an explicit this parameter, so that's all what you need to do is pass this to the std::async call and use the syntax of the member syntax function pointer when passing do_rand_stf :

 auto hand=async(launch::async,&A::do_rand_stf,this,i,j); 
However, there are other problems in the code. First, 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 named hand object without using std::move . Or just pass the async result to push_back directly:
 ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j)); 
+36
Aug 01 2018-12-12T00:
source share

You can pass the this pointer to a new thread:

 async([this]() { Function(this); }); 
+1
Feb 12 '17 at 22:15
source share



All Articles