【发布时间】:2020-09-17 18:41:21
【问题描述】:
我有一个 boost io_service 在线程中运行,我想在客户端发生特定事件 6 秒后在该线程中触发回调,如果该客户端已经在运行,则重置该客户端的计时器。
我为每个客户维护一个带有计时器的unordered_map<string, shared_ptr<deadline_timer>>。
但是,在设置 async_wait 后,我的回调不会在分配的时间后触发(io_service 正在运行),当我重置指针(应该调用)时它也不会触发(带有错误代码)现有计时器的析构函数,使其发布到服务)。我该如何解决这个问题?
这是我的代码的相关部分:
auto it = timersByClientId.find(clientId);
if (it == timersByClientId.end())
{
onLogonChangeCallback(clientId, true);
timersByClientId[clientId].reset(
new boost::asio::deadline_timer(replyService, boost::posix_time::seconds(6))
);
it = timersByClientId.find(clientId);
}
else
{
// Cancel current wait operation (should fire the callback with an error code)
it->second.reset(
new boost::asio::deadline_timer(replyService, boost::posix_time::seconds(6))
);
}
it->second->async_wait([this, clientId](const boost::system::error_code& err) {
if (!err)
{
onLogonChangeCallback(clientId, false);
}
});
如果它改变了什么,我在 Visual C++ 2010 和 boost 1.47.0 下运行。
【问题讨论】:
-
我要检查的第一件事是验证服务是否正在运行,并且没有因任何原因过早退出。我最常看到的是队列中没有工作,导致
run()返回。从上面的 sn-p,我看不出有什么明显的错误。 -
服务正在运行(我已经用
boost::asio::io_service::work初始化了服务),如果我从另一个来源(通过replyService.post([](){ /* something */ });调度),它会正常运行。
标签: c++ boost timer boost-asio