Pages

Boost ASIO Basic Skills

In the latest years there have been a few changes in the ASIO library, and I finally decided to review the post I have produced on it. I have downloaded the (currently) latest Boost libraries, version 1.66 (please have a look the Boost Revision History for details) and I am about to use it on a WIndows box with Visual Studio 2017 as IDE with the current (March 2018) Visual C++ programming language implementation.

In this and the next few posts, I plan to follow the Boost ASIO tutorial, basic skills section.

Notice that a few well established ASIO elements are now marked as deprecated. Define BOOST_ASIO_NO_DEPRECATED among the compiling option to get rid of them. I kept a more conservative approach, however, simply avoiding deprecations whenever I saw them.

First victim is a big one, io_service. Luckily it looks like the solution is just using io_context instead.

This led to the main change in the code for my version of the Timer.1 tutorial.

Its point is using ASIO to set a synchronous timer to block the current thread execution for a while. This is not very interesting, but shows the common pattern we are about to use to let ASIO know about a service we want it to manage on our behalf.
namespace ba = boost::asio;
namespace sc = std::chrono;

// ...

void timer1(ba::io_context& io)
{
 std::cout << "1) Starting ... " << std::flush;

 ba::system_timer timer{ io, sc::seconds(1) };  // 1
 timer.wait();  // 2

 std::cout << "done!" << std::endl;
}
1. I am creating an ASIO service, system timer, setting its delay to one second.
2. I consume the service synchronously, blocking the current thread execution.

I have used here system_timer, equivalent to the deadline_timer used in the official example, differing from it that is based on the standard C++ chrono library, instead of the boost equivalent one. If you need a steady clock, use steady_timer.

I have pushed the reviewed code for this example on GitHub. I have added a main in an another file, that would run all the examples in this section.

No comments:

Post a Comment