Search code examples
c++asynchronous

Launch asyc a method from a class in C++


I am using C++14 and would like to launch a method from a class instance which is stored in unique_ptr. A very simple version of my code looks like:

class foo {
  void run_server() {
    // Do some stuff.
  }
};

auto ptr = make_unique<foo>();
auto res = std::async(std::launch::async, ptr->run_server());

I get compile error when I compile my code and the error message says that there is no match to call async. I think there is a way to launch methods of an instantiated class using lambda function but I am not sure how or whether this is a solution in my case. Any help is appreciated. Thanks.


Solution

  • You can use a lambda to achieve this BUT passing a unique_ptr to a lambda means you move it to lambda and then it is destroyed when the lambda returns.

    You could try this:

    class foo {
    public:
        void run_server() {
            // Do some stuff.
        }
    };
    
    int somefunc() {
        auto ptr = std::make_unique<foo>();
        auto p = ptr.get();
    
        auto theasync=std::async( std::launch::async, [p]{ p->run_server() ;});
        //do whatever...
        return 0;
    }