我有一个定期运行的 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_timer
是 not 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/