Ive got an application where I want to display a frame every x milliseconds.
Previously I did it like this:
class SomeClass
{
boost::thread thread_;
boost::timer timer_;
public:
SomeClass() : thread_([=]{Display();})
{
}
void Display
{
double wait = 1.0/fps*1000.0;
while(isRunning_)
{
double elapsed = timer.elapsed()*1000.0;
if(elapsed < wait)
boost::this_thread::sleep(boost::posix_time::milliseconds(static_cast<unsigned int>(wait - elapsed)));
timer.restart();
// ... Get Frame. This can block while no frames are being rendered.
// ... Display Frame.
}
}
}
However I dont think solution has very good accuracy. I might be wrong?
I was hoping to used boost::asio::deadline_timer instead, but I'm unsure how to use it.
This is what ive tried, which doesn't seem to wait at all. It seems to just render the frames as fast as it can.
class SomeClass
{
boost::thread thread_;
boost::asio::io_service io_;
boost::asio::deadline_timer timer_;
public:
SomeClass() : timer_(io_, 1.0/fps*1000.0)
{
timer_.async_wait([=]{Display();});
thread_ = boost::thread([=]{io_.run();})
}
void Display
{
double wait = 1.0/fps*1000.0;
while(isRunning_)
{
timer_.expires_from_now(boost::posix_time::milliseconds(wait_)); // Could this overflow?
// ... Get Frame. This can block while no frames are being rendered.
// ... Display Frame.
timer_.async_wait([=]{Display();});
}
}
}
What am I doing wrong? And if I got this solution working would it be better than the first?