【发布时间】:2014-05-28 02:50:06
【问题描述】:
我正在尝试编写一个相对简单的类“CallbackTimer”,它需要一定的时间和一个函数,并且在经过一段时间后调用该函数。如有必要,可以重复几次。
这一切都按预期工作,但是当我在计时器完成之前调用 start 几次时偶尔会崩溃,但我看不出问题出在哪里。我认为这是因为我没有正确混合我的线程和 io_service,但我不确定。任何帮助或指示将不胜感激。
类如下
CallbackTimer::CallbackTimer(const std::function<void()>& callback) :
callback_(callback),
currentRepeats_(0),
//io_(boost::asio::io_service()),
timer_(new boost::asio::deadline_timer(io_)),
strand_(io_),
thread_(nullptr)
{
}
CallbackTimer::~CallbackTimer()
{
cancel();
}
void CallbackTimer::start(size_t intervalMillis, int repeats)
{
if (thread_)
{
cancel();
}
requestedRepeats_ = repeats;
intervalMillis_ = intervalMillis;
currentRepeats_ = 0;
runTimer();
thread_.reset(new std::thread([this]()
{
this->io_.run();
}));
thread_->detach();
}
void CallbackTimer::cancel()
{
timer_->cancel();
if (thread_ && thread_->joinable())
{
thread_->join();
}
io_.reset();
}
void CallbackTimer::runCallback(const boost::system::error_code& e)
{
if (e == boost::asio::error::operation_aborted)
{
io_.stop();
return;
}
currentRepeats_++;
callback_();
if (currentRepeats_ >= requestedRepeats_)
{
io_.stop();
return;
}
runTimer();
}
void CallbackTimer::runTimer()
{
timer_->expires_from_now(boost::posix_time::millisec(intervalMillis_));
timer_->async_wait(strand_.wrap(std::bind(&CallbackTimer::runCallback, this, std::placeholders::_1)));
}
【问题讨论】:
标签: c++ multithreading boost boost-asio