gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:05 25 4
gpt4 key购买 nike

假设我有一个库,它允许发出异步请求并返回一个 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<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com