在超时后销毁thread和deadline_timer对象

Where to destroy thread and deadline_timer objects after timeout?

本文关键字:deadline timer 对象 thread 超时      更新时间:2023-10-16

我的问题是关于一个正在运行的截止日期计时器,等待由相同的函数表示的一些操作完成:但我不知道,在安全完成订单后释放我的线程和截止日期对象,截止日期超时中断。什么时候能实现呢?

boost::asio::deadline_timer* mDeadline1;
boost::asio::deadline_timer* mDeadline2;
boost::thread* mThread1;
boost::thread* mThread2;
// start deadline timers
mDeadline1 = new boost::asio::deadline_timer(_io_service, boost::posix_time::seconds(2));
mDeadline1->async_wait(&MyClass::DeadlineTimedOut, this);
mDeadline2 = new boost::asio::deadline_timer(_io_service, boost::posix_time::seconds(2));
mDeadline2->async_wait(&MyClass::DeadlineTimedOut, this);

// Run operations in threads
mThread1 = new boost::thread(&MyClass::DoSomething, this);
mThread2 = new boost::thread(&MyClass::DoSomething, this);
// ...
void MyClass::DoSomething() {
  // Do something time expensive and sleep, etc. for interrupt point ...
  // which to cancel here!?
  mDeadline->cancel();
  delete mDeadline;
}
void MyClass::DeadlineTimedOut(const boost::system::error_code& pErrorCode) {
  if(pErrorCode == 0) { // deadline timed out
    // which to interrupt here?
    mThread->interrupt();
  }
  if(pErrorCode == 995) { // deadline cancelled from outside
  }
}

有人有什么建议吗?优雅,b .

计时器是没有意义的——只有你知道它们的意思和它们应该做什么——所以你必须决定取消什么。至于清理,将它们保存在scoped_ptrshared_ptr中,当范围/最后一次引用完成时,它们将自动清理。