从 Boost 1.50.0 版本开始,Boost.Thread 库对所有需要超时的操作都使用 Boost.Chrono 库,这些操作在 C++11 标准中定义。 这些操作包括(但不限于)
boost::this_thread::sleep_for
boost::this_thread::sleep_until
boost::thread
::try_join_for
boost::thread
::try_join_until
boost::condition_variable
::wait_for
boost::condition_variable
::wait_until
boost::condition_variable_any
::wait_for
boost::condition_variable_any
::wait_until
TimedLockable
::try_lock_for
TimedLockable
::try_lock_until
Boost 1.35.0 版本中引入的,使用 Boost.Date_Time 库的时间相关函数已被弃用。 这些函数包括(但不限于)
对于接受绝对时间参数的重载,需要 boost::system_time
类型的对象。 通常,这可以通过将持续时间添加到当前时间来获得,当前时间通过调用 boost::get_system_time()
获得。 例如:
boost::system_time const timeout=boost::get_system_time() + boost::posix_time::milliseconds(500); extern bool done; extern boost::mutex m; extern boost::condition_variable cond; boost::unique_lock<boost::mutex> lk(m); while(!done) { if(!cond.timed_wait(lk,timeout)) { throw "timed out"; } }
对于接受 TimeDuration 参数的重载,可以使用满足 Boost.Date_Time Time Duration 要求的任何类型的对象,例如:
boost::this_thread::sleep(boost::posix_time::milliseconds(25)); boost::mutex m; if(m.timed_lock(boost::posix_time::nanoseconds(100))) { // ... }
#include <boost/thread/thread_time.hpp> typedef boost::posix_time::ptime system_time;
请参阅 Boost.Date_Time 库中 boost::posix_time::ptime
的文档。
#include <boost/thread/thread_time.hpp> system_time get_system_time();
当前时间。
无。