Search code examples
c++boosttimerboost-thread

Share deadline_timer between two threads


I need to share a boost::deadline_timer between two threads. The boost documentation says "The shared instances are not threadsafe". Here is an example code:

ClassA : public enable_shared_from_this<ClassA>{

  ClassA()
  {
    m_timer = new boost::deadline_timer(m_io_service);
  }

  destroy()
  {
    m_timer->cancel();
    delete m_timer;
    m_timer = NULL;
  }

  thread_method()
  {
    m_timer->expire_from_now(...);
    m_timer->async_wait(...);
  }

   run()
   {
     boost::thread t(ClassA::thread_method, shared_from_this);
   }
}

My question is "To synchronize timer access between destroy() and thread_method(), can I use boost::atomic ?

Header:

boost::atomic<boost::deadline_timer*> m_timer;

Constructor:

m_timer = new boost::deadline_timer(m_io_service);

Is it thread-safe ?

Thank you.


Solution

  • No that won't help.

    The atomic only makes stores/loads of the pointer indivisible. When you dereference it, you're just accessing the deadline_timer directly, unsynchronized.

    So you can either

    • just traditional thread synchronization around all accesses to the deadline timer (e.g. using a mutex)

    • use an Asio strand to create a 'logical' thread of execution, and take care to only access the dead line timer from that strand.

    The strand approach is potentially more efficient but requires you to think about the flow of execution more accurately so you don't accidentally create a data race