Consider I have lamba foo
which just does some stuff and doesn't need to return anything.
When I do this:
std::future<T> handle = std::async(std::launch::async, foo, arg1, arg2);
Everything runs fine and the lamba will be spawned in a new thread.
However, when I don't store the std::future
which the std::async
returns, the foo will be run in the main thread and block it.
std::async(std::launch::async, foo, arg1, arg2);
What am I missing here?
The C++ standard says: The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.
One nice thing about std::async is that it manages a thread pool under the hood. So there is no worry that every time we invoke std::async a new thread is launched.
async( std::launch policy, Function&& f, Args&&... args ); (since C++20) The function template async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call.
From just::thread
documentation:
If policy is
std::launch::async
then runsINVOKE(fff,xyz...)
on its own thread. The returnedstd::future
will become ready when this thread is complete, and will hold either the return value or exception thrown by the function invocation. The destructor of the last future object associated with the asynchronous state of the returnedstd::future
shall block until the future is ready.
In
std::async(std::launch::async, foo, arg1, arg2);
The returned future is not assigned anywhere and its destructor blocks until foo
finishes.
I would like to add a link to an article by Herb Sutter on async and ~future in which he argues that futures should never block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With