使用带有boost :: asio的期货 [英] Using futures with boost::asio
问题描述
有人能很好地指出使用带有
Does anyone have a good pointer to examples which use futures from the Boost thread library with Boost ASIO? I have an existing asynchronous library which uses callback function that I would like to provide a friendlier synchronous interface for.
推荐答案
在不了解与现有异步库之间的交互作用的情况下,很难提供一个简洁的解决方案.不过,此 answer 使用Boost.Future和Boost.Asio来实现Active Object模式.当创建将来
,请考虑检查现有的异步库以确定哪种方法更合适:
It is difficult to provide a concise solution without understanding the interactions with the existing asynchronous library. Nevertheless, this answer uses Boost.Future and Boost.Asio to implement an Active Object pattern. When creating a future
, consider examining the existing asynchronous library to determine which approach is more appropriate:
- boost :: packaged_task 提供了可以创建
未来
的函子.可以在Boost.Asioio_service
的上下文中执行此函子.为了与现有的异步库集成以及解决右值语义,可能还需要一些附加的包装级别.如果当前函数调用已返回该值,请考虑使用此方法. - boost :: promise 提供了可以设置其值的较低级别的对象.可能需要修改需要接受
promise
作为参数的现有函数,并将其填充到函数中.promise
将绑定到提供给Boost.Asioio_service
的处理程序.与boost :: packaged_task
一样,可能需要附加包装级别才能处理右值语义.
- boost::packaged_task provides a functor that can create a
future
. This functor can be executed within the context of Boost.Asioio_service
. Some additional level of wrapping may be required to integrate with the existing asynchronous library, as well as work around rvalue semantics. Consider using this approach if the current function calls already return the value. - boost::promise provides a lower level object which can have its value set. It may require modifying existing functions need to accept the
promise
as an argument, and populate it within the function. Thepromise
would be bound to the handler that is provided to Boost.Asioio_service
. As withboost::packaged_task
, it may require an additional level of wrapping to deal with rvalue semantics.
最后,Boost.Asio 1.54(当前处于beta版)为
Finally, Boost.Asio 1.54 (currently in beta), provides first-class support for C++ futures. Here is the official example. Even if you are unable to currently use 1.54 beta, it may be beneficial to examine the interface and implementation.
这篇关于使用带有boost :: asio的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!