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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13669094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:37:26  来源:igfitidea点击:

How to use std::async on a member function?

c++multithreadingc++11std

提问by Avihai Marchiano

How can I operate std::async call on a member function?

如何在成员函数上操作 std::async 调用?

Example:

例子:

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

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

I want to call to sum async.

我想调用 sum async。

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

I didnt figure out if i can do it with std::async. Dont want to use boost. Looking for a one line async call way.

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

回答by juanchopanza

Something like this:

像这样的东西:

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

or

或者

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

where pis a Personinstance and xxxis an int.

其中p是一个Person实例,xxxint

This simple demo works with GCC 4.6.3:

这个简单的演示适用于 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";
}

回答by Johan Lundberg

There are several ways, but I find it's most clear to use a lambda, like this:

有几种方法,但我发现使用 lambda 最清楚,如下所示:

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

This creates a std::future. For a complete example of this, I have a full example including a async-capable setup of mingw here:

这将创建一个std::future. 对于一个完整的例子,我有一个完整的例子,包括一个支持异步的 mingw 设置:

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

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

You need to make sure that p is thread safe and that the &p reference is valid until the async is joined. (You can also hold p with a shared pointer, or in c++14, a unique_ptr or even move p into the lambda.)

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