使用Posix时间的Boost中的线程超时

时间:2012-07-31 23:38:57

标签: c++ boost

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

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

所以,我正在考虑使用内置的posix_time类来计算每个线程的截止日期。这样,总等待时间最多为给定的超时时间。

最简单,最直接的方法是什么?

2 个答案:

答案 0 :(得分: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的教程。

答案 1 :(得分:0)

int64_t mseconds = 60*1000; // 60 seconds

只需使用

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

你不需要使用绝对时间