Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who is responsible for the shared state of futures and promises

Who owns the shared state in futures and promises? In particular who is responsible for the construction and deletion of the shared state in these classes? Or is the shared state supposed to be reference counted? I am not able to get an answer by reading the docs for these on cppreference.

The way I was thinking about it the easiest thing to do would be to have the std::promise class be responsible for the creation of the shared state, but then hand it off to the std::future that is fetched from the std::promise for deletion when the future is destroyed. But then this approach can lead to dangling promise objects. So I am not sure how really the state is supposed to be shared between the two.

For example does the code below produce undefined behavior (since the shared state might be destroyed when the future is destroyed)?

auto prom = std::promise<void>{};
{
    auto fut = prom.get_future();
}
prom.set_value();

Further, the docs for std::promise::~promise on cppreference say "if the shared state is ready, releases it" which gets me to think that the shared state is not reference counted.

like image 605
Curious Avatar asked Apr 13 '17 04:04

Curious


People also ask

Are futures and promises the same?

Specifically, when usage is distinguished, a future is a read-only placeholder view of a variable, while a promise is a writable, single assignment container which sets the value of the future.

How does STD future work?

The class template std::future provides a mechanism to access the result of asynchronous operations: An asynchronous operation (created via std::async, std::packaged_task, or std::promise) can provide a std::future object to the creator of that asynchronous operation.

What are futures programming?

In programming, a future is an abstraction for a value that may be available at some point in the future. Once the future has resolved, its value becomes available immediately. If we request the value of a future that has not yet resolved the request blocks leading our program to wait until the value becomes available.

What is STD promise?

The class template std::promise provides a facility to store a value or an exception that is later acquired asynchronously via a std::future object created by the std::promise object.


1 Answers

When the std::future (or std::promise) is destroyed, it releases its shared state.

This rule states that when an asynchronous return object or an asynchronous provider is said to release its shared state, it gives up its reference to the shared state.

If that reference was the last one, the shared state is destroyed.

So yes, shared state seems to be reference counted and no, your code example does not produce UB since prom still holds a reference to the shared state.

like image 71
Ap31 Avatar answered Nov 15 '22 11:11

Ap31