async: Start Policy
This lesson gives an overview of start policy used with std::async in C++ for multithreading.
With the start policy you can explicitly specify whether the asynchronous call should be executed in the same thread (std::launch::deferred
) or in another thread (std::launch::async
).
Eager versus lazy evaluation
Eager and lazy evaluations are two orthogonal strategies to calculate the result of an expression. In the case of eager evaluation, the expression will be evaluated immediately; In the case of lazy evaluation, the expression will only be evaluated if needed. Eager evaluation is often called greedy evaluation and lazy evaluation is often called call-by-need. With lazy evaluation, you save time and compute power because there is no evaluation on suspicion.
By default, std::async
executes its work package immediately. This is why it’s called eager evaluation.
What is special about the call auto fut= std::async(std::launch::deferred, ... )
is that the promise will not be executed immediately. The call fut.get()
starts the promise lazily; i.e. the promise will only run if the future asks via fut.get()
for the result.
Get hands-on with 1200+ tech skills courses.