asio io_service
は、のスケジュールのタイマーイベントを実行すると、適切なタイミングでコールバックします。ここで
は完全な例である:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using namespace std;
class timed_class
{
public:
timed_class(boost::asio::io_service& io_service) : _timer(io_service)
{
// now schedule the first timer.
_timer.expires_from_now(boost::posix_time::milliseconds(100)); // runs every 100 ms
_timer.async_wait(boost::bind(&timed_class::handle_timeout, this, boost::asio::placeholders::error));
}
void handle_timeout(boost::system::error_code const& cError)
{
if (cError.value() == boost::asio::error::operation_aborted)
return;
if (cError && cError.value() != boost::asio::error::operation_aborted)
return; // throw an exception?
cout << "timer expired" << endl;
// Schedule the timer again...
_timer.expires_from_now(boost::posix_time::milliseconds(100)); // runs every 100 ms
_timer.async_wait(boost::bind(&timed_class::handle_timeout, this, boost::asio::placeholders::error));
}
private:
boost::asio::deadline_timer _timer;
};
int main(void)
{
boost::asio::io_service io_service;
timed_class t(io_service);
io_service.run();
return 0;
}
EDIT:タイムアウトが経過した後に別のスレッドで派遣する、
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
代わりのio_service.run();
、今メインスレッドは継続となり、 io_service
はhandle_timeout
出典
2010-12-07 07:00:53
Nim
あなたのインターバルはどれくらい短いですか? –