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

标签 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);
}

我想调用异步求和。

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

我不知道我是否可以使用 std::async 来做到这一点。 不想使用升压。 寻找单行异步调用方式。

最佳答案

类似这样的:

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";
}

关于c++ - 如何在成员函数上使用 std::async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13669094/

相关文章:

C++ OpenGL 相机运动

Linux 上的 Java BlockingQueue 延迟高

c++ - 存储指针 vector 的最佳 C++11 方法

c++ - 直接初始化与值初始化

c++ - 在 Structure from Motion 中进行三角剖分后

c++ - 验证整数输入 C++?

c++ - 从类模板派生类

c# - c#有更好的等待模式吗?

c++ - 在多个线程中重写方法

c++ - 扩展 std::tuple 以用作类的初始化程序