I am using a std::future<T>
to store the result of an optionally asynchronous operation. Depending on arguments to a function the operation is either asynchronous or synchronous. In the synchronous case I have a value that I want to store in a future
. How do I best do this?
Examples given in https://en.cppreference.com/w/cpp/thread/future is:
future
from apackaged_task
future
from anasync()
future
from apromise
But there isn't a make_future
, nor does the future
constructor allow creating a fulfilled future
from a value. So I created a helper function for doing just that, by going through a promise
like this:
template <typename T>
std::future<T> make_future(T&& t)
{
std::promise<T> p;
p.set_value(std::forward<T>(t));
return p.get_future();
}
Is this a valid way to create a std::future<T>
from a T
?
Is there a better way to create a std::future<T>
from a T
?
EDIT: Example, cache:
Foo readAndCacheFoo(int id);
std::future<Foo> readFooAsync(int id)
{
{
const lock_guard lock{cacheMutex};
if (id == cachedId)
{
return make_future(cachedFoo);
}
}
return std::async(readAndCacheFoo, id);
}
std::future
which is not associated to thestd::promise
? – Parklandstd::packaged_task
, get the future from it, execute the task and return the future? – Silkweedstd::future
useful in general. Has too little functionality and slow. There are many ways you can store result of an ansynchronous/synchronous process withoutstd::future
. – Foliolestd::variant<std::reference_wrapper<Foo>,std::future<Foo>>
and return a future only when it is not cached. Othewise, return a reference to the cached object. Need to admit that I don't know whether there isn't some standard/pattern solution of this problem. – Planimetry