I'm assuming there's something very simple I'm missing about std::async
. I'm trying to run 2 void
methods asynchronously, with no return values.
#include <future>
class AsyncTestClass {
public:
void Initialize()
{
std::async(&AsyncTestClass::AsyncMethod1);
std::async(&AsyncTestClass::AsyncMethod2);
}
void AsyncMethod1()
{
//time consuming operation
}
void AsyncMethod2()
{
//time consuming operation
}
};
But get an error when calling my AsyncMethod1
or AsyncMethod2
within std:async
:
Substitution failed: type 'typename std:conditional<sizeof....(ArgTypes) == 0, std::_Invoke_traits_Zero<void, typename std::decay.....is ill formed with _Fty = void (AsyncTestClass::*)(), _ArgTypes =
What is the proper usage of std:async
with void
, parameterless methods? The examples I see seem similar to how I'm using it, but it's not working for me.
AsyncTestClass::AsyncMethod1
, being a non-static member function, can only be called if an instance of AsyncTestClass
is supplied. You probably meant this:
std::async(&AsyncTestClass::AsyncMethod1, this)
This creates a std::future
object whose value will be obtained by evaluating this->AsyncMethod1()
.
By the way, the return value of std::async
should be assigned to a variable, otherwise the call will block. See std::async won't spawn a new thread when return value is not stored. If you have C++20, the compiler will catch this for you thanks to [[nodiscard]]
.