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


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 

2 个解决方案

#1


39  

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參數的仿函數,所以你需要做的就是將它傳遞給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 #includeing <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:

但是,代碼中還有其他問題。首先,在沒有#includeing 的情況下使用std :: cout和std :: endl。更嚴重的是,std :: future不可復制,只能移動,所以你不能在不使用std :: move的情況下push_back命名對象的手。或者,只需將異步結果直接傳遞給push_back:

ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));

#2


2  

You can pass the this pointer to a new thread:

您可以將this指針傳遞給新線程:

async([this]()
{
    Function(this);
});

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com