multithreading - 从另一个线程原子地取消 asio 异步计时器

标签 multithreading boost timer cancellation

我有一个定期运行的 boostdeadline_timer(如示例 http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tuttimer3/src.html ):

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(const boost::system::error_code& /*e*/,
    boost::asio::deadline_timer* t)
{
    t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
    t->async_wait(boost::bind(print,
          boost::asio::placeholders::error, t, count));
}

int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
  t.async_wait(boost::bind(print,
        boost::asio::placeholders::error, &t));

  io.run();

  return 0;
}

现在我需要从另一个线程取消它。
但是如果取消调用只出现在打印函数执行期间但在 expires_at 调用之前呢?然后计时器将继续运行。

处理它的一种方法是运行类似
while (timer.cancel() == 0) {
}

在那个单独的线程函数中。

但也许有人知道更优雅的方式可以解决这个问题?

最佳答案

其实这两种方式都不太安全,只是因为deadline_timernot thread-safe .

IMO,最简单安全的方式是post取消:

//...
timer.get_io_service().post([&]{timer.cancel();})
//...

注意:在真正的代码中必须确保 timer比仿函数(lambda)长。

更新:正如@sehe 提到的,这个解决方案可能不起作用 - 因为取消处理程序可能出现在 io_service 中就在前面的队列 print ,当计时器不再等待时。

关于multithreading - 从另一个线程原子地取消 asio 异步计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047765/

相关文章:

iphone - 如何在 iPhone 中重置倒计时?

java - Thread.sleep() 没有按预期触发

c++ - 一个简单的win32多线程代码。这行得通吗?

.net - 当我的代码没有出现在堆栈中时,如何调试此错误?

multithreading - 我可以使用多少个后台工作人员?

c++ - 使用 boost::bind 的调用错误没有匹配函数

c++ - 为什么编译Boost时使用 "arm-linux-gnueabi-g++"?

c++ - 如何删除 boost 图的子图

c++ - 如何确保例程按时执行?

C# 定时器间隔每 24 小时