c++ - 使用 boost::asio::deadline_timer 实现通用 Timer 类时遇到问题

标签 c++ boost

在 UI 应用程序上实现计时器类。

基本上,我遇到的问题是调用io.run()会阻塞,导致async_wait调用无用。通过阅读其他帖子,我得到的印象是 Timer,或者至少是调用 startCountdown 的代码,应该位于另一个线程上。

下面是我的代码。我如何以 Boost 中认为正确的方式管理此问题?

class Timer
{
public:

    Timer() : countdownTimer(io) {  }

    void startCountdown(int seconds)
    {
        countdownTimer.expires_from_now(boost::posix_time::seconds(seconds));
        countdownTimer.async_wait(boost::bind(&Timer::on_timeout, this, _1));
        io.run(); // this blocks
    }

    void on_timeout(const boost::system::error_code& e)
    {
        if (e != boost::asio::error::operation_aborted) {
            cout << "Timer expired!";
        }
    }

private:

    boost::asio::io_service io;
    boost::asio::deadline_timer countdownTimer;
}

最佳答案

您不应该调用 io_servicerun 成员函数,而应该调用以下之一:

取决于您的设计目标。

另请注意,boost Asio 并不是真正设计为用于某些功能的辅助库,而是作为程序的核心元素,它更像是脊柱而不是 ARM 。

专用于处理与 io_service 相关的所有内容的线程也可以工作,但祝您在同步和异步世界之间同步共享数据好运:)

关于c++ - 使用 boost::asio::deadline_timer 实现通用 Timer 类时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907208/

相关文章:

c++ - 预声明类型定义的 boost::variant

c++ - 汇编指令的正则表达式

c++ - 找出类(class)及其 child 中的类(class)类型

c++ - boost::uint32_t != std::uint32_t 对于 ARM 目标

c++ - 使用 LSB C++ 编译器构建 Boost

c++ - 如何确保在修改 .h 文件时,包含该文件的 .cc 文件会在使用 Visual Studio 2008 的发布版本中自动编译?

c++ - cgi 不适用于 boost 正则表达式

c++ - 使用指针或引用返回 Boost 矩阵有优势吗?

C++11 gcc : explicit qualification in declaration? 标准引用?

java - 查找范围内元素数量的最快方法