efficient handling of synchronous case

You can have an async API like this

std::future<int> GetAsync()

There are cases when for example you already have the result cached and would like to return the future initialized with the result. Is there a way with current standard (or proposal) to achieve that without recurring to creating an additional std::promise or making an additional async (with launch policy deferred) ?

EDIT

Consider also the case when result is computed based on some state local to GetAsync() function and the need to capture that probably by value in case one chooses to use std::async with launch policy deferred


I'm obviously misunderstanding something, why can't you just do this:

std::future<int> GetAsync()
{
  if (/*already got result*/)
  {
    std::promise<int> p;
    p.set_value(/*result*/);
    return p.get_future();
  }  
  return std::async(/*whatever is needed*/);
}

What is wrong with creating a promise? If you want to get a result from a future (an asynchronous return object) you need an asynchronous provider, a promise is such a type.


The thing with futures and promises is they are designed for multi-threaded usage. So if you want to return a future object you need to create it either via a std::async call, a std::packaged_task<> or a std::promise<> . If that's the case @ronag's answer is a hit.

If this is not a general case and you just want to return an indirection to your value you may use a std::function for direct computation, or a caching mechanism around it, or an Expected<T> value for handling errors too like the futures does; so you won't pay for the thread communication costs.

链接地址: http://www.djcxy.com/p/30742.html

上一篇: 将未来存储在列表中

下一篇: 高效处理同步案例