...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
This tutorial program introduces asio by showing how to perform a blocking wait on a timer.
We start by including the necessary header files.
All of the asio classes can be used by simply including the "asio.hpp"
header file.
#include <iostream> #include <boost/asio.hpp>
Since this example uses timers, we need to include the appropriate Boost.Date_Time header file for manipulating times.
#include <boost/date_time/posix_time/posix_time.hpp>
All programs that use asio need to have at least one io_service object. This class provides access to I/O functionality. We declare an object of this type first thing in the main function.
int main() { boost::asio::io_service io;
Next we declare an object of type boost::asio::deadline_timer. The core asio classes that provide I/O functionality (or as in this case timer functionality) always take a reference to an io_service as their first constructor argument. The second argument to the constructor sets the timer to expire 5 seconds from now.
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
In this simple example we perform a blocking wait on the timer. That is, the call to deadline_timer::wait() will not return until the timer has expired, 5 seconds after it was created (i.e. not from when the wait starts).
A deadline timer is always in one of two states: "expired" or "not expired". If the deadline_timer::wait() function is called on an expired timer, it will return immediately.
t.wait();
Finally we print the obligatory "Hello,
world!"
message to show when the timer has expired.
std::cout << "Hello, world!\n"; return 0; }
See the full source listing
Return to the tutorial index