简体   繁体   中英

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...

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM