I tried to test how std::shared_future is shared between different threads as these threads all calls its wait() function, and wake up after its signal is called. As below:
#include <iostream>
#include <future>
using namespace std;
int main() {
promise<void> p, p1, p2;
auto sf = p.get_future().share(); // This line
auto f1 = [&]() {
p1.set_value();
sf.wait();
return 1;
};
auto f2 = [&]() {
p2.set_value();
sf.wait();
return 2;
};
auto ret1 = async(launch::async, f1);
auto ret2 = async(launch::async, f2);
p1.get_future().wait();
p2.get_future().wait();
p.set_value();
cout << ret1.get() << ", " << ret2.get();
return 0;
}
The program prints 1, 2 and works fine.
Then I changed the line of auto sf = p.get_future().share(); into auto sf = p.get_future() using oridinay future object, not the shared version, compile and run. I got the same result: while I expected that for the non-shared version, only 1 thread will successfully wait and return while other threads will hang. But seems still the program runs OK.
So my question is: when do we need to use std::shared_future instead of std::future? Or it's just an object like std::shared_ptr, as a simple wrapper of std::future so that it could be passed around?
I mean is there any case that non-shared future doesn't fulfill the need or scenario. Would you help to explain?