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;
}
}
(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.
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.
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.
To reuse promises, simply reassign them. it should be my_promise = std::promise<int>() not my_promise = std::my_promise<int>() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With