Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...