如何对成员函数进行 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);
其中 p
是 Person
实例,xxx
是 int
。
这个简单的演示适用于 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/