Async futures and performance
Futures returned by std::async
behave differently from the ones obtained from promises when their destructors are called. When these futures are destroyed, their ~future
destructor is called where the wait()
function is executed, causing the thread that was spawned at creation to join.
That would impact the program performance by adding some overhead if the thread used by std::async
has not already been joined, therefore we need to understand when the future object will go out of scope and thus its destructor will be called.
Let’s see, with several short examples, how these futures behave and some recommendations on how to use them.
We start by defining a task, func
, that simply multiplies its input value by 2 and also waits for some time, emulating a costly operation:
#include <chrono> #include <functional> #include <future> #include <iostream> #include <thread> #define sync_cout std::osyncstream(std::cout...