【问题标题】:Futures vs. Promises期货与承诺
【发布时间】:2012-09-19 04:02:36
【问题描述】:

我对未来和承诺之间的区别感到困惑。

显然,它们有不同的方法和内容,但实际用例是什么?

是吗?:

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

【问题讨论】:

标签: c++ c++11 promise future


【解决方案1】:

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();

使用 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);
}

std::promise 周围使用std::packaged_task 作为助手(即它基本上完成了我们上面所做的工作),您可以执行以下更完整且可能更快的操作:

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);
}

请注意,这与std::async 略有不同,std::future 在被破坏时实际上会阻塞,直到线程完成。

【讨论】:

  • @taras 建议返回 std::move(something) 是没有用的,而且还会伤害 (N)RVO。恢复他的编辑。
  • 在 Visual Studio 2015 中请使用 std::cout
  • 还有疑惑的朋友请看this answer
  • 这是一次性生产者 - 消费者,恕我直言,这并不是真正的生产者 - 消费者模式。
猜你喜欢
  • 2015-07-17
  • 1970-01-01
  • 2013-06-22
  • 2013-09-28
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多