使用需要绝对时间(即时间点)而不是持续时间的thread::timed_join
的超负荷。使绝对时间最后期限为当前时间加上任何你想要的超时时间。这将确保循环中的thread::timed_join
调用都不会等待超过绝对时间的最后期限。
在最新版本的Boost.Thread(截止到Boost 1.50)中,Boost.Date_Time现在已被弃用,赞成Boost.Chrono。这与C++ 11中的std::thread的API更接近。
这个例子显示了如何既Boost.Chrono或Boost.DateTime指定一个绝对的截止时间:
using namespace boost;
#if BOOST_VERSION < 105000
// Use of Boost.DateTime in Boost.Thread is deprecated as of 1.50
posix_time::ptime deadline =
posix_time::microsec_clock::local_time() +
posix_time::seconds(timeoutSeconds);
#else
chrono::system_clock::time_point deadline =
chrono::system_clock::now() + chrono::seconds(timeoutSeconds);
#endif
for(int i = 0; i < number_of_threads; ++i)
{
threads[i]->timed_join(deadline);
}
这page文档中显示的Boost.Date_Time示例用法。
本文档中的page是关于Boost.Chrono的教程。