Reputation: 194
I wonder in which case std::launch::deferred
is required.
As far as i know, the purpose of multi-threading is that another thread would take care of something or calculation in the background and return a value when the task is finished. It should start off as soon as the thread is created. With that being said, why do we need this type of deferred launch?
Upvotes: 2
Views: 233
Reputation: 9991
You can switch a program from multithreaded to single threaded with a flag for debugging purposes.
//const auto launchPolicy = std::launch::async;
const auto launchPolicy = std::launch::deferred;
void doThings(){
auto fut = async(launchPolicy, []{ thing1(); });
thing2();
fut.wait();
}
Without the const
you can even change the behavior at runtime. It is not perfect though, single threaded mode can cause a deadlock.
Upvotes: 0
Reputation: 70402
With that being said, why do we need this type of deferred launch?
This question is similar to asking why &&
and ||
operators have short-circuiting behavior. The short-circuiting behavior will cause the RHS of the expression in the test to go unevaluated if the result of the operation is determined by the LHS. Short-circuiting behavior could be expressed by using multiple if
statements instead. So the language offers more than one way to express the same idea.
Similarly, the software component may be more clearly expressed by showing all the tasks involved, even if not all the tasks are actually performed because component completed its job without requiring the other tasks. Certainly, the software could be written differently by just not expressing the tasks until they actually need to run.
As an example, the code may initialize an array of tasks, and iterate over them with a loop. However, an early break
from the loop will avoid executing the remaining tasks.
Upvotes: 3
Reputation: 5980
You could use deferred launching when you only may need the result of an operation. For instance, you could do the following, and the future will be evaluated iff get()
or wait()
is called.
int SomeFunction()
{
// ....
std::future<int> futLazy = std::async( std::launch::deferred, []{ return SomeComplexOperation(); });
if( GetSomeCondition() )
{
// Do something involving futLazy.get()
}
return 1;
}
In this example, SomeComplexOperation()
will only be called if GetSomeCondition()
returns true
. So this is just a method of queuing operations to be evaluated if and only if required.
Upvotes: 0