c++ - 需要对 Boost asio 异步操作和计时器进行一些说明

标签 c++ boost boost-asio

异步连接中定时器有一个方面我想知道我是否理解正确。

假设我们在执行读取操作之前设置了一个计时器,其中包括一个处理程序,然后,run() io_service。

据我所知,io_service 在管理器被调用后一结束就结束,这可能有两个原因:

a) 读操作完成。

b) 计时器已达到其限制。

假设第一个(a)条件已经达到,并且在定时器结束前读操作已经完成。

问题是:那个计时器会发生什么?我们需要完成它吗?说

dTimer_.expires_from_now (boost::posix_time::seconds(0));

after the io_service.run()?

如果需要重新使用同一个计时器对象进行另一个读取操作,您能否将其重置为新的时间间隔?

我可以重置() io_service 并在新的 run() 中为该新操作重用相同的对象吗?

最佳答案

The question is: What happens to that timer? Do we need to finish it.

如果您不这样做,计时器的处理程序仍将被调用 cancel

void my_read_handler() {
     dTimer_.cancel(); // remember to catch exceptions
}

async_wait 处理程序 将被传递一个 error codeboost::asio::error::operation_aborted 如果成功取消。如果 async_waitcancel 之前完成并且处理程序已经被 io_service 排队,您​​的处理程序将需要检测该情况并做出适当的 react .


Can you reset it to a new interval if necessary re-use the same timer object for another read operation?

deadline_timer 可以是 reset使用 expires_from_now

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.


Can I reset() the io_service and reuse the same object in a new run() for that new operation?

相同的io_service 对象可以在resetting 之后再次用于run()poll()

This function must be called prior to any second or later set of invocations of the run(), run_one(), poll() or poll_one() functions when a previous invocation of these functions returned due to the io_service being stopped or running out of work. This function allows the io_service to reset any internal state, such as a "stopped" flag.

关于c++ - 需要对 Boost asio 异步操作和计时器进行一些说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5116402/

相关文章:

linux - 即使异步 I/O 操作挂起,也只有处理 io_service 的线程在等待

c++ - 我如何只从 C++ 中的 stdin/cin 读取一个空格?

c++ - 服务器关闭永远不会完成

c++ - 如何在数据以二进制零结尾时初始化 std::string

c++ - Boost::Bind 和虚函数重载:它们为什么起作用?

c++ - Boost.Serialization 和 Boost.Python 双向 pickle

c++ - boost::asio::ssl::context::add_verify_path

c++ - 使用函数指针和引用推导模板参数

java - boost::multiprecision::powm 不同于 Java 中的 BigInteger#modPow

c++ - boost::asio async_read_some async_read_until 编译器警告