如何在成员函数上使用std :: async?

时间:2012-12-02 12:02:15

标签: c++ multithreading c++11 std

如何在成员函数上运行std :: async调用?

示例:

class Person{
public:
    void sum(int i){
        cout << i << endl;
    }
};

int main(int argc, char **argv) {
    Person person;
    async(&Person::sum,&person,4);
}

我想调用sum async。

Person p;
call async to p.sum(xxx)

我没弄明白我是否能用std :: async做到这一点。 不想使用提升。 寻找一行异步呼叫方式。

2 个答案:

答案 0 :(得分:27)

这样的事情:

auto f = std::async(&Person::sum, &p, xxx);

auto f = std::async(std::launch::async, &Person::sum, &p, xxx);

其中pPerson个实例,而xxxint

这个简单的演示适用于GCC 4.6.3:

#include <future>
#include <iostream>

struct Foo
{
  Foo() : data(0) {}
  void sum(int i) { data +=i;}
  int data;
};

int main()
{
  Foo foo;
  auto f = std::async(&Foo::sum, &foo, 42);
  f.get();
  std::cout << foo.data << "\n";
}

答案 1 :(得分:14)

有几种方法,但我发现使用lambda最清楚,就像这样:

int i=42;
Person p;
auto theasync=std::async([&p,i]{ return p.sum(i);});

这会创建一个std::future。有关这方面的完整示例,我有一个完整的示例,包括mingw的异步功能设置:

http://scrupulousabstractions.tumblr.com/post/36441490955/eclipse-mingw-builds

您需要确保p是线程安全的,并且&amp; p引用在加入异步之前有效。 (您也可以使用共享指针保存p,或者使用c ++ 14,使用unique_ptr或者将p移动到lambda中。)