Search code examples
c++std-functionstdasync

How can I pass this std::function to std::async


I am working on a piece of multi threaded code but I can't seem to pass a std::function object to the std::async function. I'm sure I am doing something wrong but I can't figure out what that would be. Therefore, I prepared this piece of code so maybe someone who knows could help me.

Test1 demonstrates that this std::function object works.
Test2 contains the thing I want it to do; only I wrapped the function object into a lambda.
Test3 contains the example I can't figure out.

std::function<void(AsyncFunctionExample&)> current_function;

void Test1() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    current_function(*this);
}

void Test2() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async([&](){current_function(*this);});
}

void Test3() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async(current_function, *this);
}

The full code for this example can be found here. The Stackoverflow editor Warned that I am not allowed to dump a full file of code so that's why I boiled it down to its essentials over here.

The compiler error I receive is:
no matching function for call to 'async(std::function&, AsyncFunctionExample&)' const std::future function_future = std::async(current_function, *this);

This doesn't help me a lot. It basically explains to me that there is no signature that matches my call. But I can't figure out from this error what part of my call is wrong and I don't understand how to change it so it would work.


Solution

  • You can't pass a reference through std::async as it needs to copy the value. You can fix this with std::ref:

    const std::future<void> function_future = std::async(current_function, std::ref(*this));
    

    Alternatively just change your function to:

    std::function<void(AsyncFunctionExample*)> current_function;
    

    Then you can pass this directly:

    const std::future<void> function_future = std::async(current_function, this);