【问题标题】:Time-out for Threads in Boost using Posix TimeBoost 中使用 Posix 时间的线程超时
【发布时间】:2012-07-31 23:38:57
【问题描述】:

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

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

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    使用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 的教程。

    【讨论】:

      【解决方案2】:
      int64_t mseconds = 60*1000; // 60 seconds
      

      简单地使用

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

      你不需要使用绝对时间

      【讨论】:

        猜你喜欢
        • 2014-05-10
        • 2016-10-01
        • 1970-01-01
        • 2015-03-08
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        • 2017-04-24
        • 2012-10-11
        相关资源
        最近更新 更多