jeudi 5 novembre 2020

Canceling asio::steady_timer in owner object's destructor

I have some encapsulated logic managed by asio::steady_timer. There are no needs to invoke this logic after 'real end of object life'. It means no needs to extend object life to last invoking of timer's completion handler. Can I cancel the timer in object's destructor and no wait when completion handler will be invoked?

#include <memory>
#include <thread>

#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>

namespace asio = boost::asio;

class Foo : public std::enable_shared_from_this<Foo>
{
public:
  explicit Foo(asio::io_context& ioc)
    : m_timer(ioc)
  {}

  ~Foo()
  {
    std::lock_guard<std::mutex> lock(m_mutex);
    m_timer.cancel();
  }

  void update()
  {
    std::lock_guard<std::mutex> lock(m_mutex);

    m_timer.expires_after(std::chrono::seconds(1));
    m_timer.async_wait(
      [=](const boost::system::error_code& ec)
      {
        if (!ec) {
          update();
        }
      }
    );

    // ...
  }

private:
  mutable std::mutex m_mutex;
  asio::steady_timer m_timer;
};

int main()
{
  asio::io_context ioContext;

  auto foo = std::make_shared<Foo>(ioContext);

  foo->update();

  std::thread thread(
    [&]
    {
      ioContext.run();
    }
  );

  foo.reset();

  thread.join();

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire