asio 0.1.5 Main Page | Class Index | Member Index | Tutorial

Tutorial Part 2 - Using a timer asynchronously

This tutorial program demonstrates how to use asio's asynchronous callback functionality by modifying the program from Part 1 to perform an asynchronous wait on the timer.

#include <iostream>
#include "asio.hpp"

Step 1. Using asio's asynchronous functionality means having a callback function that will be called when an asynchronous operation completes. In this program we define a function called print to be called when the asynchronous wait finishes.

void print()
{
  std::cout << "Hello, world!\n";
}

int main()
{
  asio::demuxer d;

  asio::timer t(d, asio::timer::from_now, 5);

Step 2. Next, instead of doing a blocking wait as in Part 1, we call the async_wait function to perform an asynchronous wait. When calling this function we pass the print callback handler that was defined above.

  t.async_wait(print);

Step 3. Finally, we must call the asio::demuxer::run() member function on the demuxer object.

The asio library provides a guarantee that callback handlers will only be called from threads that are currently calling asio::demuxer::run(). Therefore unless the asio::demuxer::run() function is called the callback for the asynchronous wait completion will never be invoked.

The asio::demuxer::run() function will also continue to run while there is still "work" to do. In this example, the work is the asynchronous wait on the timer, so the call will not return until the timer has expired and the callback has completed.

  d.run();

  return 0;
}

See the Source listing for Tutorial Part 2
Return to the Tutorial Index
Go back to Tutorial Part 1 - Using a timer synchronously
Go on to Tutorial Part 3 - Binding arguments to a handler