我有一个应用程序,我希望每x毫秒显示一个帧。准确的连续计时器回调
以前我做的是这样的:
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.
}
}
}
不过,我不认为解决方案有很好的精度。我可能错了?
我希望能用boost :: asio :: deadline_timer代替,但我不确定如何使用它。
这是我试过的,这似乎没有等待。它似乎只是尽可能快地渲染帧。
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();});
}
}
}
我在做什么错?如果我得到这个解决方案的工作会比第一个更好吗?
我不熟悉这个语法'timer_.async_wait([=] {显示();});'它有什么作用? – 2010-07-26 14:40:23
如果你的意思是[=] {Display();}),那么它只是一个C++ 11x lambda表达式。它是写函数对象的简写。 – ronag 2010-08-06 18:14:34