Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 587
MrEvil Avatar asked Jun 24 '13 18:06

MrEvil


People also ask

Does boost ASIO use threads?

If the run() method is called on an object of type boost::asio::io_service, the associated handlers are invoked on the same thread. By using multiple threads, an application can call multiple run() methods simultaneously.

Is boost ASIO cross platform?

Boost. Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.

Who is using Boost ASIO?

The project is sponsored by Automatak. The stack uses a completely asynchronous design. The core library is written in C++11 and has abstracted execution services, timers, and physical layers called the Platform Abstraction Layer (PAL).

Is boost ASIO header only?

By default, Boost. Asio is a header-only library. However, some developers may prefer to build Boost. Asio using separately compiled source code.


1 Answers

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.

like image 128
Tanner Sansbury Avatar answered Oct 12 '22 16:10

Tanner Sansbury