我正在尝试用 C++ 创建一个秒表,类似于 Java 的TimerTask。我喜欢他们的库,因为它已经内置了线程。我见过Boost Chrono,但是,它仍在开发中,不想使用它。
我目前的实现一直没有运气(我现在正在记忆中,所以这可能有点像伪代码)。
boost::asio::io_service io;
boost::asio::deadline_timer timer(io);
Initialize()
{
boost::shared_ptr<boost::thread> thread = boost::shared_ptr<boost::thread>(
new boost::thread(
boost::bind(&boost::asio::io_service::run, &io)
);
}
Start()
{
timer.async_wait(
bind(&HandleTimerEvent, this, asio::placeholders::error)
);
}
Stop()
{
timer.cancel
}
Tick()
{
cout << "THE TIME IS: " << timer.current_time << endl; // Pseudo code for current_time.
}
HandleTimerEvent(boost::system::error_code& e)
{
cout << "Timer has ended: " << e << endl;
}
我想要的是让线程不断调用Tick()
并打印出当前时间。此外,我当前的实现似乎让线程阻塞了应用程序的其余部分,这是我绝对不想要的。我将如何做这两件事?
在线程方面我是个菜鸟,所以如果我说了一些看起来不正确的话,请原谅我。