3

我使用 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 类来计算每个线程的截止日期。这样,总等待时间最多是给定的超时时间。

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

4

2 回答 2

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);
}

文档中的此页面显示了 Boost.Date_Time 示例用法。

文档中的这个页面是关于 Boost.Chrono 的教程。

于 2012-08-01T01:22:55.813 回答
0
int64_t mseconds = 60*1000; // 60 seconds

只需使用

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

你不需要使用绝对时间

于 2013-11-20T19:46:07.083 回答