gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:53:23 47 4
gpt4 key购买 nike

如何对成员函数进行 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/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com