Boost logo

Boost Users :

Subject: Re: [Boost-users] multithreaded timer?
From: Igor R (boost.lists_at_[hidden])
Date: 2009-03-26 11:37:54


> As far as I could understand, the deadline_timer just runs once, i.e.,
> if I would like to use it multiple times, I have to instantiate new ones everytime.

It's absolutely incorrect. Did you see asio exmaples/reference? On
expiration or cancellation the timer invokes its handler - in the
thread(s) of its io_service. Then you can start the same timer again:

  //...
  timer.expires_from_now(boost::ptime::seconds(5));
  time.async_wait(&handler);
  //...
void handler()
{
  // start it again:
  timer.expires_from_now(boost::ptime::seconds(10));
  timer.async_wait(&handler);
}

>
> It needs to be turned on inside a separate thread, the command queue
> one, when it sends a serial command, and if the answer arives before
> the timer is due, it has to be turned off, again inside that separate
> queue thread, so it doesn't hit the "resend".

The timer itself is not thread-safe, i.e. you have to start/cancel it
from the thread(s) of its io_service. The most convenient way to deal
with it is to make your queue processing io_service-based -- then you
can just supply the same io_service to the timer.
If it's not possible, you can perform timer-related operations from
your queue thread by re-posting them to the timer thread, no locking
is needed:

void doCancel()
{
  timer.cancel();
}
void cancelFromAnotherThread()
{
  timer.get_io_service().post(&doCancel);
}

...and when timer handler is invoked (on timer.io_service thread), you
just have to synchronize an access to your queue data, if needed.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net