Use of shared_future in C++ 11

Use of shared_future in C++ 11

The shared_future object works similar to std::future except that it can be copied and thereby more than one std::future can share the ownership. The use of shared_future in C++ is explained in two steps:

#Problem statement:

In the below example, when a user tries to get future value multiple times, it results in an exception. The value from the future can only be retrieved only once and when a user tries to invoke get() API multiple times, it throws an exception.

int work(future &fu)
{
    try
    {
        this_thread::sleep_for(chrono::milliseconds(1000));
        double Result1 = fu.get();
        cout << "Child::Result1 : " << Result1 << endl;

        double Result2 = fu.get();
        cout << "Child::Result2 : " << Result2 << endl;
    }
    catch (exception &ex)
    {
        cerr << ex.what() << endl;
    }

    return 10;
}
int main()
{
    promise p;
    future fu = p.get_future();
    future<int> fr = async(launch::async, work, ref(fu));
    p.set_value(20.5);

    fr.get();
    return 0;
}

Output:

Child::Result1 : 20.5
no state

#Solution: Use of shared_future in C++

To overcome the above problem, std::shared_future can be used, as it copies value and thereby allows the user to invoke get() multiple times as required.

int work(shared_future fu)
{
    this_thread::sleep_for(chrono::milliseconds(1000));
    double Result1 = fu.get();
    cout << "Child::Result1 : " << Result1 << endl;


    double Result2 = fu.get();
    cout << "Child::Result2 : " << Result2 << endl;

    return 10;
}
int main()
{
    promise p;
    shared_future fu = p.get_future();

    shared_future<int> fr = async(launch::async, work, fu);
    p.set_value(20.5);


    int result1 = fr.get();
    cout << "Parent::Result1 : " << result1 << endl;


    int result2 = fr.get();
    cout << "Parent::Result2 : " << result2 << endl;
    return 0;
}

Output:

Child::Result1 : 20.5
Child::Result2 : 20.5
Parent::Result1 : 10
Parent::Result2 : 10