Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::async won't spawn a new thread when return value is not stored

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?

like image 484
Stephan Dollberg Avatar asked Feb 28 '12 21:02

Stephan Dollberg


People also ask

Does async create a new thread C++?

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.

Does STD async create new thread?

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.

What does STD async return?

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.


2 Answers

From just::thread documentation:

If policy is std::launch::async then runs INVOKE(fff,xyz...) on its own thread. The returned std::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 returned std::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.

like image 101
Wojciech Cierpucha Avatar answered Oct 13 '22 18:10

Wojciech Cierpucha


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.

like image 30
Micha Wiedenmann Avatar answered Oct 13 '22 20:10

Micha Wiedenmann