假设我有一个库,允许发出异步请求并返回 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::future
或implement it yourself .
关于c++ - (如何)当 std::future 准备好时,我可以在 boost::asio::io_service 上获得回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769056/