Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to destroy a std::promise before future.get() is called?

I was wondering if it is ok to call promise.get_future(), move that future somewhere else (e.g. into a vector) and possibly let the promise die before even the future.get() is called. In the following example, the call gateway->refreshWithCallback executes the lambda in a thread so that the shared pointer may set the promise free even if in the second loop the future.get() was not called yet, which seems to work but I am angsty!

std::vector<std::future<bool>> futures;
for(GuiGateway *gateway : gateways){
    std::shared_ptr<std::promise<bool>> shared_promise_ptr(new std::promise<bool>());
    futures.push_back(shared_promise_ptr.get()->get_future());
    gateway->refreshWithCallback([shared_promise_ptr](bool success){
        shared_promise_ptr.get()->set_value(success);
    });
}

qDebug() << "waiting for futures";

for(std::future<bool> &future : futures){
    if(future.get() == false){
        qDebug() << "error retrieving all gateway data, aborting auto config";
        return;
    }
}
like image 892
Magnus Lutz Avatar asked Jan 23 '18 18:01

Magnus Lutz


People also ask

What is std :: future in C++?

(since C++11) 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 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.

What function is used to set the return value in a future promise channel once the running thread has exited?

The answer is using std::future object. Every std::promise object has an associated std::future object, through which others can fetch the value set by promise.

How can you reuse STD promises?

To reuse promises, simply reassign them. it should be my_promise = std::promise<int>() not my_promise = std::my_promise<int>() .


1 Answers

If you provide a value to the std::promise before destroying it, the associated std::future will be able to retrieve it just fine. It does not depend on std::promise still existing. If you failed to provide a value to std::promise before destroying it, trying to get a result from the std::future will throw std::future_error but it is also well defined.

like image 87
François Andrieux Avatar answered Oct 24 '22 19:10

François Andrieux