c++ - (如何)当 std::future 准备好时,我可以在 boost::asio::io_service 上获得回调吗?

标签 c++ c++11 boost boost-asio future

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

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

最佳答案

通过使用then,您可以指定当 future 准备好时要执行某些操作:

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::futureimplement it yourself .

关于c++ - (如何)当 std::future 准备好时,我可以在 boost::asio::io_service 上获得回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769056/

相关文章:

c++如何使用boost xml解析器读取XML并存储在 map 中

c++ - 如何更新 boost multi_index_container 的值?

c++ - 为什么需要双指针来更改头部而不是链接列表中的其他地方

c++ - 类中的变量正在自行重置

c++ - 为什么将 std::basic_streambuf* 插入 ostream 会插入缓冲区内容?

c++ - 函数模板的显式实例化何时发生实例化

c++ - Doxygen 支持 C++11 模板别名( 'using' 语法)?

c++ - 循环性能内部评估的 bool 条件

c++ - 删除和默认函数真实世界的例子

c++ - CMake:尝试将链接库添加到未在此目录中构建的目标