Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between future and shared_future?

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

  1. future object could be queried only once for the get().
  2. 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...

like image 633
Ajeet Ganga Avatar asked Apr 14 '13 23:04

Ajeet Ganga


1 Answers

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.

like image 127
Howard Hinnant Avatar answered Nov 13 '22 07:11

Howard Hinnant