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

后端 未结 2 1451
醉梦人生
醉梦人生 2020-12-06 03:44

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

Example:

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


        
相关标签:
2条回答
  • 2020-12-06 04:34

    Something like this:

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

    or

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

    where p is a Person instance and xxx is an int.

    This simple demo works with 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";
    }
    
    0 讨论(0)
  • 2020-12-06 04:45

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

    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:

    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.)

    0 讨论(0)
提交回复
热议问题