首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在成员函数上使用std::async?

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

Stack Overflow用户
提问于 2012-12-02 20:02:15
回答 2查看 39.3K关注 0票数 40

如何在成员函数上操作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做到这一点。不想使用boost。寻找一种单线异步调用方式。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-02 20:04:06

如下所示:

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

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

其中pPerson实例,xxxint

这个简单的demo与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";
}
票数 47
EN

Stack Overflow用户

发布于 2012-12-02 20:05:27

有几种方法,但我发现使用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是线程安全的,并且&p引用在异步连接之前是有效的。(您也可以使用共享指针来保存p,或者在c++14中使用unique_ptr,甚至可以将p移到lambda中。)

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13669094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档