Waiting asynchronously

As a first approach to ASIO make sense to write a minimal program that performs a synchronous wait on an ASIO timer, as I did in a previous post. But more interesting is setting an asynchronous wait, as we are going to see here.

What I want to do here is executing a couple of actions. One has to be delivered after a certain amount of time, so I set a timer on ASIO, and ask to its I/O service to run a function when it expires. The other can be executed right away, so I'll do it in the main code, after setting the timer on ASIO, but before asking the ASIO I/O service to run.

The function that I want ASIO to execute when the timer expires is:
void hello(const boost::system::error_code& ec) // 1
    std::cout << "delayed hello [" << ec.value() << ']'  << std::endl;
1. ASIO is going to pass to to function the timer exit status. Usually we should check it, and let our code to behave differently if the timer expired correctly or with an error. A zero error code means (as for the old C tradition) success. Here I simply output its value to the user.

And that's the code snippet where ASIO is set up and run:
boost::asio::io_service aios; // 1

boost::asio::steady_timer timer(aios, std::chrono::seconds(1)); // 2
timer.async_wait(hello); // 3
std::cout << "hello" << std::endl; // 4
aios.run(); // 5
1. Create the ASIO I/O Service
2. Create a one second timer on the service
3. Run the timer asynchronously, specifying that we want to run the hello() function when it expires.
4. Do something else.
5. Pass the control to ASIO. It would keep it until it has something to do. Here we have instruct it only to take care of the timer. As soon it is done with it, it would return the control back.

If we don't get first the hello message as by (4) and then the delayed hello message as by (3), we should start to worry.

Full C++ source code, with minor variations, is on github.

No comments:

Post a Comment