我使用的是Boost 1.66.0,其中asio内置了对与 future 进行互操作的支持(并且有一段时间)。我在网上看到的示例说明了在使用诸如async_readasync_read_some等网络功能时如何干净地实现此目的。这是通过提供 boost::asio::use_future 代替完成处理程序来完成的,这会导致启动函数按预期返回future

我需要提供或包装函数的哪种对象才能从boost::asio::post获得相同的行为?

我发布工作的目的是在一小段上下文中执行它,但是要等到工作完成,这样我才能得到想要的行为:

std::packaged_task<void()>  task( [] { std::cout << "Hello world\n"; } );
auto  f = task.get_future();
boost::asio::post(
    boost::asio::bind_executor(
        strand_, std::move( task ) ) );
f.wait();

但是根据boost::asio文档,以与 boost::asio::post 之类的函数相同的方式推导 boost::asio::async_read 的返回类型,因此我觉得必须有一种更好的方法来避免中间packaged_task。与async_read不同,post不需要完成“其他工作”,因此仅提供boost::asio::use_future是没有道理的,但是我们可以定义async_result特性来获得相同的发布行为。

是否有包装器或已定义必要特征以获取我想要的行为的东西,或者我需要自己定义它?

最佳答案



你不能post是无效操作。因此,实际上,使用post实现此目标的唯一选择是使用打包任务。

真正的问题

它隐藏在“如何获得相同的行为”部分中(只是不是来自post):

template <typename Token>
auto async_meaning_of_life(bool success, Token&& token)
{
    using result_type = typename asio::async_result<std::decay_t<Token>, void(error_code, int)>;
    typename result_type::completion_handler_type handler(std::forward<Token>(token));

    result_type result(handler);

    if (success)
        handler(error_code{}, 42);
    else
        handler(asio::error::operation_aborted, 0);

    return result.get ();
}

您可以在将来使用它:
std::future<int> f = async_meaning_of_life(true, asio::use_future);
std::cout << f.get() << "\n";

或者,您可以只使用处理程序:
async_meaning_of_life(true, [](error_code ec, int i) {
    std::cout << i << " (" << ec.message() << ")\n";
});

简单演示: Live On Coliru

扩展演示

相同的机制扩展到支持协程(有或没有异常(exception))。 Asio boost 版1.66.0的async_result舞蹈略有不同。

在这里一起查看所有不同的形式:
  • How to set error_code to asio::yield_context

  • Live On Coliru
    #define BOOST_COROUTINES_NO_DEPRECATION_WARNING
    #include <iostream>
    #include <boost/asio.hpp>
    #include <boost/asio/spawn.hpp>
    #include <boost/asio/use_future.hpp>
    
    using boost::system::error_code;
    namespace asio = boost::asio;
    
    template <typename Token>
    auto async_meaning_of_life(bool success, Token&& token)
    {
    #if BOOST_VERSION >= 106600
        using result_type = typename asio::async_result<std::decay_t<Token>, void(error_code, int)>;
        typename result_type::completion_handler_type handler(std::forward<Token>(token));
    
        result_type result(handler);
    #else
        typename asio::handler_type<Token, void(error_code, int)>::type
                     handler(std::forward<Token>(token));
    
        asio::async_result<decltype (handler)> result (handler);
    #endif
    
        if (success)
            handler(error_code{}, 42);
        else
            handler(asio::error::operation_aborted, 0);
    
        return result.get ();
    }
    
    void using_yield_ec(asio::yield_context yield) {
        for (bool success : { true, false }) {
            boost::system::error_code ec;
            auto answer = async_meaning_of_life(success, yield[ec]);
            std::cout << __FUNCTION__ << ": Result: " << ec.message() << "\n";
            std::cout << __FUNCTION__ << ": Answer: " << answer << "\n";
        }
    }
    
    void using_yield_catch(asio::yield_context yield) {
        for (bool success : { true, false })
        try {
            auto answer = async_meaning_of_life(success, yield);
            std::cout << __FUNCTION__ << ": Answer: " << answer << "\n";
        } catch(boost::system::system_error const& e) {
            std::cout << __FUNCTION__ << ": Caught: " << e.code().message() << "\n";
        }
    }
    
    void using_future() {
        for (bool success : { true, false })
        try {
            auto answer = async_meaning_of_life(success, asio::use_future);
            std::cout << __FUNCTION__ << ": Answer: " << answer.get() << "\n";
        } catch(boost::system::system_error const& e) {
            std::cout << __FUNCTION__ << ": Caught: " << e.code().message() << "\n";
        }
    }
    
    void using_handler() {
        for (bool success : { true, false })
            async_meaning_of_life(success, [](error_code ec, int answer) {
                std::cout << "using_handler: Result: " << ec.message() << "\n";
                std::cout << "using_handler: Answer: " << answer << "\n";
            });
    }
    
    int main() {
        asio::io_service svc;
    
        spawn(svc, using_yield_ec);
        spawn(svc, using_yield_catch);
        std::thread work([] {
                using_future();
                using_handler();
            });
    
        svc.run();
        work.join();
    }
    

    打印
    using_yield_ec: Result: Success
    using_yield_ec: Answer: 42
    using_yield_ec: Result: Operation canceled
    using_yield_ec: Answer: 0
    using_yield_catch: Answer: 42
    using_future: Answer: 42
    using_yield_catch: Caught: Operation canceled
    using_future: Answer: using_future: Caught: Operation canceled
    using_handler: Result: Success
    using_handler: Answer: 42
    using_handler: Result: Operation canceled
    using_handler: Answer: 0
    

    关于c++ - 我如何从boost::asio::post获得 future ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49950679/

    10-15 05:50