期货与承诺

Let*_*_Be 124 c++ future promise c++11

我把自己与未来和承诺之间的区别混淆了.

显然,他们有不同的方法和东西,但实际的用例是什么?

是吗?:

  • 当我管理一些异步任务时,我使用future来"获取未来"的价值
  • 当我是异步任务时,我使用promise作为返回类型,以允许用户从我的承诺中获得未来

ron*_*nag 155

Future和Promise是异步操作的两个独立方面.

std::promise 由异步操作的"生产者/编写者"使用.

std::future 由异步操作的"使用者/读者"使用.

将它分成这两个独立的"接口"的原因是隐藏 "消费者/读者"的"写入/设置"功能.

auto promise = std::promise<std::string>();

auto producer = std::thread([&]
{
    promise.set_value("Hello World");
});

auto future = promise.get_future();

auto consumer = std::thread([&]
{
    std::cout << future.get();
});

producer.join();
consumer.join();
Run Code Online (Sandbox Code Playgroud)

使用std :: promise实现std :: async的一种(不完整的)方法可能是:

template<typename F>
auto async(F&& func) -> std::future<decltype(func())>
{
    typedef decltype(func()) result_type;

    auto promise = std::promise<result_type>();
    auto future  = promise.get_future();

    std::thread(std::bind([=](std::promise<result_type>& promise)
    {
        try
        {
            promise.set_value(func()); // Note: Will not work with std::promise<void>. Needs some meta-template programming which is out of scope for this question.
        }
        catch(...)
        {
            promise.set_exception(std::current_exception());
        }
    }, std::move(promise))).detach();

    return std::move(future);
}
Run Code Online (Sandbox Code Playgroud)

使用std::packaged_task哪个是帮手(即它基本上就是我们上面做的那样)std::promise你可以做以下更完整,可能更快的事情:

template<typename F>
auto async(F&& func) -> std::future<decltype(func())>
{
    auto task   = std::packaged_task<decltype(func())()>(std::forward<F>(func));
    auto future = task.get_future();

    std::thread(std::move(task)).detach();

    return std::move(future);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这与std::asyncstd::future破坏实际阻塞之前返回的内容略有不同,直到线程完成.

  • 对于仍然感到困惑的人,请参阅[此答案](http://stackoverflow.com/questions/11004273/what-is-stdpromise/12335206#12335206). (4认同)
  • @taras建议返回`std :: move(something)`是没有用的,并且还会伤害(N)RVO。还原他的编辑。 (2认同)
  • 这是一次性的生产者 - 消费者,恕我直言,并不是真正的生产者 - 消费者模式. (2认同)