Book Image

Boost.Asio C++ Network Programming

By : Wisnu Anggoro
Book Image

Boost.Asio C++ Network Programming

By: Wisnu Anggoro

Overview of this book

Table of Contents (15 chapters)
Boost.Asio C++ Network Programming Second Edition
Credits
About the Authors
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Timing the work execution using the timer class


There is a class in the Boost C++ library that provides the ability to conduct a blocking or asynchronous wait for a timer until it expires, known as the deadline timer. A deadline timer indicates one of two states: expired or not expired.

An expiring timer

Here, we are going to create a timer that will expire in 10 seconds. Let us take a look at the following code:

/* timer.cpp */
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <iostream>

boost::mutex global_stream_lock;

void WorkerThread(boost::shared_ptr<boost::asio::io_service> iosvc, int counter) {
  global_stream_lock.lock();
  std::cout << "Thread " << counter << " Start.\n";
  global_stream_lock.unlock();

  while(true) {
    try {
      boost::system::error_code ec;
      iosvc->run(ec);
      if(ec) {
        global_stream_lock...