Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does an asio timer go out of scope?

What I mean is, let's say you do an async_wait on an asio timer and bind the update to a function that takes a reference to a type T. Let's say you created the T initially on the stack before passing it to async_wait. At the end of that async_wait, it calls async_wait itself, renewing the timer over and over. Does that stack allocated type T stay alive until the first time the timer doesn't renew itself, or after the first invocation of the function will the T go out of scope?

like image 302
ApplePieIsGood Avatar asked Mar 13 '10 01:03

ApplePieIsGood


1 Answers

If you were to write a function in which you create a timer on the stack, then call async_wait, the timer would be destroyed at the end of the function call, and the callback immediately called with the proper error parameter.

You cannot pass the timer object to the callback using boost::bind, as the object is non copyable.

Nevertheless, you can manage your binder on the heap, passing a shared pointer on each call to async_wait. This could look like this:

void MyClass::addTimer(int milliseconds) // Initial timer creation call
{
  boost::shared_ptr<boost::asio::deadline_timer> t
    (new boost::asio::deadline_timer
     (m_io_service, 
      boost::posix_time::milliseconds(milliseconds)));
  // Timer object is being passed to the handler
  t->async_wait(boost::bind(&MyClass::handle_timer,
                            this,
                            t,
                            milliseconds));

}

void MyClass::handle_timer(boost::shared_ptr<boost::asio::deadline_timer> & t,
                               int milliseconds)
{
  // Push the expiry back using the same tick
  t->expires_at(t->expires_at() + boost::posix_time::milliseconds(milliseconds));
  t->async_wait(boost::bind(&MyClass::handle_timer,
                            this,
                            t,
                            milliseconds));
  onTimer(); // Do something useful
}
like image 147
small_duck Avatar answered Oct 20 '22 02:10

small_duck