I saw the uses of std::future in the program written in C++. So, I quickly went to lookup what is is: std::future and got a quite complicated answer for me.
Can someone put it in simple words for a 6 years old kid? I have an understanding level of a 6 years old kid...
Just a small definition with a minimal use case will work for me. Let me know if it is too much to ask and I'll take back my question.
A std::future<T> is a handle to a result of work which is [potentially] not, yet, computed. You can imagine it as the receipt you get when you ask for work and the receipt is used to get the result back. For example, you may bring a bike to bike store for repair. You get a receipt to get back your bike. While the work is in progress (the bike being repaired) you can go about other business. Eventually, when the work is supposed to be done you ask for the result (the repaired bike) and [potentially] wait until the result is delivered.
std::future<T> is a general mechanism to receive result. It doesn't prescribe how the requested work is actually executed.
There is a quite simple example on the cppreference page you linked. Slightly modified:
std::future<int> f = std::async(std::launch::async, []{
// long calculation
return /* some result */;
});
/* do some other stuff */
int result = f.get();
std::async with the std::launch::async flag runs a function (here a lambda) asynchronously (in another thread). It returns a std::future, which will eventually, when that function finishes, contain an int value.
While that function is running, we can go on and /* do some other stuff */.
When we need the result, we call f.get() which waits until the int value is available, meaning until the asynchronous function has finished, and then gives it to us. The value f.get() gives us is the function's return value which std::async stored in the std::future after the function returned.
Instead of std::async it may also be used with threads via std::promise or std::packaged_task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With