期货与承诺

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

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

是吗?:

  • 当我pipe理一些asynchronous任务时,我将来会用“未来”
  • 当我是asynchronous任务时,我使用promise作为返回types,以允许用户从我的承诺中获得未来

未来和承诺是asynchronous操作的两个独立方面。

std::promise被asynchronous操作的“producer / writer”使用。

std::future被asynchronous操作的“消费者/读者”使用。

它被分成这两个单独的“接口”的原因是为了隐藏 “消费者/阅读器”的“写/设置”function。

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

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