Using futures with boost::asio

10,734

Solution 1

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 provides a functor that can create a future. This functor can be executed within the context of Boost.Asio io_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. The promise would be bound to the handler that is provided to Boost.Asio io_service. As with boost::packaged_task, it may require an additional level of wrapping to deal with rvalue semantics.

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.

Solution 2

Can you please look at this example:

http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp11/futures/daytime_client.cpp

It shows how to use std::future with boost asio.

The key point is to include file use_future.hpp:

#include <boost/asio/use_future.hpp>

Then you can write code like that:

std::future<std::size_t> my_future =
    my_socket.async_read_some(my_buffer, boost::asio::use_future);

If you need to use boost::future then I'd suggest to implement another variant, similar to boost::asio::use_future.
The file use_future.hpp is a good example for that.

Share:
10,734
MrEvil
Author by

MrEvil

Updated on July 18, 2022

Comments

  • MrEvil
    MrEvil almost 2 years

    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.

  • Alexander Stepaniuk
    Alexander Stepaniuk about 7 years
    well, such solution is actively used on on my project. And it works. Are you sure you really know the reason of blocking asio in your case?
  • kralyk
    kralyk over 6 years
    Apparently that code in the example blocks on each future. What's the point of using futures if you just block on each one? Might as well just use blocking code in the first place...