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

Viewed 35415

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.

#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 
2 Answers
Related