2012-07-31 14 views
3

我使用Boost线程库在C++中创建了多个线程, 我想超时所有这些线程,我可以在循环中使用timed_join(),但是可以使总等待时间=线程数*超时。使用Posix时间在Boost中线程超时

for(int i = 0; i < number_of_threads; ++i) 
{ 
    threads[i]->timed_join(boost::posix_time::seconds(timeout_time)); 
} 

所以,我想使用内置的posix_time类来计算每个线程的截止日期。这样总的等待时间至多是给定的超时时间。

什么是最简单和最直接的方法来做到这一点?

回答

7

使用需要绝对时间(即时间点)而不是持续时间的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的教程。

0
int64_t mseconds = 60*1000; // 60 seconds 

只需使用

threads[i]->timed_join(boost::posix_time::milliseconds(mseconds)) 

你不需要使用绝对时间