gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:55 31 4
gpt4 key购买 nike

在 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 实现通用定时器类时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907208/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com