Search code examples
c++boostboost-threadstopwatch

C++ Threaded Stopwatch


I am trying to create a stopwatch in C++, something similar to Java's TimerTask. I like their library since it already has threading built in. I have seen Boost Chrono, however, it's still in development and would prefer not to use it.

My current implementation has been without luck (I am going by memory right now so this might be a little pseudo code like).

boost::asio::io_service io;
boost::asio::deadline_timer timer(io);


Initialize()
{
  boost::shared_ptr<boost::thread> thread = boost::shared_ptr<boost::thread>(
      new boost::thread(
        boost::bind(&boost::asio::io_service::run, &io)
  );
}

Start()
{
   timer.async_wait(
       bind(&HandleTimerEvent, this, asio::placeholders::error)
   );
}

Stop()
{
  timer.cancel
}

Tick()
{
   cout << "THE TIME IS: " << timer.current_time << endl; // Pseudo code for current_time.
}

HandleTimerEvent(boost::system::error_code& e)
{
  cout << "Timer has ended: " << e << endl;
}

What I would like to have is to have the thread continuously call Tick() and print out the current time. Also, my current implementation seems to have the thread as blocking the rest of the application which is something I definitely don't want. How would I do both of these things?

I am a noob when it comes to threading so please forgive me if I stated something that doesn't seem right.


Solution

  • You nearly have it, because you're creating a new thread to handle io_service::run(), your main thread will not block. Two things you need to do,

    1. ensure you call Start() before you Initialize() (using the same io_service instance), this way there is something for the io_service to do, else it will quit!
    2. On your HandleTimer() method, call async_wait again to queue up the next tick, else io_service will quit as it has nothing to do..