Does promise.get_future() have to be called before setting a value?
Asked Answered
S

1

8

From http://www.cplusplus.com/reference/future/promise/get_future/:

After this function has been called, the promise is expected to make its shared state ready at some point [...]

I'm unsure if this implies that this order of operations is mandatory:

  1. get_future()
  2. set_value()

Would it also be possible to get the future from the promise only after a value has been set?

Seneca answered 15/5, 2019 at 10:30 Comment(5)
Can you show an example where it would make sense to call set_value before get_future?Anathematize
@mike Let's say I create a promise, pass it to some other thread (e.g. by capturing it by reference in a lambda which is then executed on some thread), and then basically do promise.get_future().get().Seneca
@FelixDombek Are you sure that doesn't have a data race?Osber
@Osber I don't think it matters. If set_value can be called after the call to get_future, then get() will just either wait or return immediately. So no matter whether the thread executes first or second, this line should be safe.Seneca
As we can see in C++ standard issues, calling get_future & set_value may produce a data race.Wheelwork
G
4

As far as I see there is no such limitation. The only two cases when std::promise::set_value leads to error are:

  1. Promise object has no shared state (this can occur when promise object is being moved):

    promise<int> p;
    auto p2 = std::move(p);
    p.set_value(42); // error
    
  2. The shared state already stores a value or exception:

    promise<int> p;
    p.set_value(0);
    p.set_value(42); // error
    

    or

    promise<int> p;
    try 
    {
        throw std::runtime_error("Some error");
    } 
    catch(...) 
    {
        p.set_exception(std::current_exception());
        p.set_value(42); // error
    }
    

But there is no limitation for get_future to be called before.

Gnosticism answered 15/5, 2019 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.