C ++中类成员的class和std :: async [英] Class and std::async on class member in C++

查看:192
本文介绍了C ++中类成员的class和std :: async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个可并行调用另一个类成员的类成员。

I'm try to write a class member which calls another class member multiple times in parallel.

我写了一个简单的问题示例,甚至不能编译一下。调用std :: async我在做什么错?我想问题可能出在我如何传递函数上。

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();
}

编译:

g++ -std=c++11 -pthread main.cpp 


推荐答案

do_rand_stf 是非静态成员函数,因此如果没有类实例,则无法调用(隐式这个参数。)幸运的是, std :: async 处理其参数,例如 std :: bind bind 依次可以使用 std :: mem_fn 将成员函数指针转换为函子一个显式的 this 参数,因此您要做的就是将 this 传递给 std :: async 调用,并在传递 do_rand_stf 时使用有效的成员函数指针语法:

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:

auto hand=async(launch::async,&A::do_rand_stf,this,i,j);

尽管如此,代码中还有其他问题。首先,使用 std :: cout std :: endl 而不使用 #include ing < iostream> 。更严重的是, std :: future 不可复制,只能移动,因此不能 push_back 命名对象 hand ,而不使用 std :: move 。或者,只需将 async 结果直接传递给 push_back

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:

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

这篇关于C ++中类成员的class和std :: async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆