我怎样才能从boost :: asio :: post获得未来?

时间:2018-04-20 22:55:35

标签: c++ boost boost-asio future

我正在使用Boost 1.66.0,其中asio内置支持与期货的互操作(现在已经有一段时间了)。我在网上看到的示例说明了在使用async_readasync_read_some等网络功能时如何干净利落地实现这一点。这可以通过提供boost::asio::use_future代替完成来完成handler,它使初始化函数按预期返回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不同,没有&#34;其他工作&#34;由post完成,因此只提供boost::asio::use_future没有意义,但我们可以定义一个async_result特征来获得相同的帖子行为。

是否有一个包装器或某些东西具有定义的必要特征以获得我想要的行为或我需要自己定义它?

2 个答案:

答案 0 :(得分:3)

  

我需要提供什么样的对象或将我的函数包装起来以从boost::asio::post获取相同的行为?

你不能。 post是一个无效操作。因此,使用post实现它的唯一选择是使用打包任务,真的。

真实问题

隐藏在部分&#34;如何获得相同的行为&#34; (不是来自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";
});

简单演示: https://github.com/Studio-42/elFinder/wiki/Getting-encoded-hash-from-the-path

扩展演示

同样的机制扩展到支持协同程序(有或没有例外)。对于Asio pre-boost 1.66.0,async_result的舞蹈略有不同。

在这里一起查看所有不同的表格:

<强> How to set error_code to asio::yield_context

#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

答案 1 :(得分:0)

根据我的想法,它实际上包装了asio::post并插入了一个promise / future对。我认为它也可以适应您的需求。

// outer scope setup
asio::io_context context;
asio::io_context::strand strand(context);


std::future<void> async_send(tcp::socket& socket, std::string message) {
    auto buffered = std::make_shared<std::string>(message);
    std::promise<void> promise;
    auto future = promise.get_future();

    // completion handler which only sets the promise.
    auto handler = [buffered, promise{std::move(promise)}](asio::error_code, std::size_t) mutable {
        promise.set_value();
    };

    // post async_write call to strand. Thas *should* protecte agains concurrent 
    // writes to the same socket from multiple threads
    asio::post(strand, [buffered, &socket, handler{std::move(handler)}]() mutable {
        asio::async_write(socket, asio::buffer(*buffered), asio::bind_executor(strand, std::move(handler)));
    });
    return future;
}

可以在不使未来失效的情况下兑现承诺。

适应您的情况可能是这样的:

template<typename C>
std::future<void> post_with_future(C&& handler)
{
    std::promise<void> promise;
    auto future = promise.get_future();

    auto wrapper = [promise{std::move(promise)}]{ // maybe mutable required?
         handler();
         promise.set_value();
    };

    // need to move in, cause the promise needs to be transferred. (i think)
    asio::post(strand, std::move(wrapper)); 
    return future;
}

我很乐意对这些内容进行一些反馈,因为我自己只是在学习整个过程:)

希望有帮助, 马蒂