Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::async - std::launch::async | std::launch::deferred

Tags:

c++

c++11

future

I understand what std::async does with the following parameters.

  • std::launch::async
  • std::launch::deferred

However what happens with, std::launch::async | std::launch::deferred?

like image 903
ronag Avatar asked Feb 20 '12 10:02

ronag


People also ask

Does STD async start a new thread?

If the deferred flag is set, a callable function will be stored together with its arguments, but the std::async function will not launch a new thread.

How does STD async work?

std::async() does following things, It automatically creates a thread (Or picks from internal thread pool) and a promise object for us. Then passes the std::promise object to thread function and returns the associated std::future object.


1 Answers

A launch policy of std::launch::async | std::launch::deferred means that the implementation can choose whether to apply a policy of std::launch::async or std::launch::deferred. This choice may vary from call to call, and may not be decided immediately.

An implementation that always chooses one or the other is thus legal (which is what gcc does, always choosing deferred), as is one that chooses std::launch::async until some limit is reached, and then switches to std::launch::deferred.

It also means that the implementation can defer the choice until later. This means that the implementation may wait to make a decision until its hand is forced by a call that has visibly distinct effects from deferred and async tasks, or until the number of running tasks is less than the internal task limit. This is what just::thread does.

The functions that force the decision are: wait(), get(), wait_for(), wait_until(), and the destructor of the last future object referencing the result.

like image 108
Anthony Williams Avatar answered Oct 11 '22 18:10

Anthony Williams