(如何)当 std::future 准备就绪时,我能否在 boost::asio::io_service 上获得回调?

(How) Can I get a callback on a boost::asio::io_service when a std::future is ready?

假设我有一个允许发出异步请求和 returns 一个 std::future 查询结果(状态)的库。我想将该库与 boost::asio::io_service 集成,以便在未来准备就绪后立即在 io_service 循环中调用回调。有什么方法可以在不更改库或在 io 循环中定期轮询未来的情况下实现这一目标?

注意:有几个问题处理反向问题,即在 io_service 上的某些操作完成时获取准备就绪的 std::future(例如 Program to read asynchronously in boost asio with C++11 future).我找不到实现完全相反的方法,即在 future 准备好时在 io_service 上执行回调。

通过使用 then,您可以指定在未来准备就绪时执行某些操作:

future<T> my_future = lib::get_some_future();
my_future.then([] (future<T> f) {
    do_something_with_io_service(f.get())
}); // .then returns a new future (future<void> in this case) that allows chaining

但是请注意,从 C++11 开始,std::future 缺少一个 then 成员函数。您可以改为使用 boost::future or implement it yourself.

如何产生一个守护线程来完成这项工作,如下所示:

#include <future>
#include <memory>
#include <thread>
#include <utility>
#include <boost/asio.hpp>

template <class Callback, class T>
void post_when_ready(boost::asio::io_service& iosvc,
                     std::shared_ptr<std::future<T>> ptr,
                     Callback callback) {
  std::thread{
    [=, &iosvc] {
      ptr->wait();
      // ...
      iosvc.post(std::move(callback));
    }
  }.detach();
}