What is the difference between future
and shared_future
?
In what cases we must use shared_future
instead of future
?
I was trying to find good documentation that will contrast these two features of C++11, and I could not find an answer (easy/readable at least) on the web.
This is my current understanding of the differences
future
object could be queried only once for the get()
.shared_future
could be queried any number of times.use case:
If multiple threads are dependent on the result of an asynchronous task, then we must use shared_future
.
If the future object needs be queried multiple times in the same thread then we must use shared_future
instead.
Any more information, gotchas or general guidelines are welcome...
The motivation for these two future types goes back to move semantics, move-only types, and the new C++11 feature to return move-only types from ordinary functions.
In C++98/03, if you wanted to return a type from a factory function:
A
make_A()
{
A a;
// ...
return a;
}
then A
had to be CopyConstructible
. Then, brand new in C++11, we can return A
even if it is not CopyConstructible
, it need only be MoveConstructible
.
But what happens if you try to execute make_A
concurrently, say using futures. Wouldn't it be a crime if you could only parallelize make_A
if A
is CopyConstructible
?! You would have to give up one optimization while chasing another!
So future<R>
only requires R
to be MoveConstructible
. But you can only get it once, because you're moving from the stored result.
But getting the same result for multiple threads is a real need too. So shared_future<R>
allows that, but requires R
to be CopyConstructible
.
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