[英]Time-out for Threads in Boost using Posix Time
I have created a number of threads in C++ using the Boost Threads library, I want to time-out all these threads, I can use the timed_join()
in a loop, but this can make the total waiting time = number-of-threads * time-out-time. 我使用Boost Threads库在C ++中创建了许多线程,我想超时所有这些线程,我可以在循环中使用
timed_join()
,但这可以使总等待时间=线程数*超时时间。
for(int i = 0; i < number_of_threads; ++i)
{
threads[i]->timed_join(boost::posix_time::seconds(timeout_time));
}
So, I'm thinking of using the builtin posix_time class to calculate the deadline for each thread. 所以,我正在考虑使用内置的posix_time类来计算每个线程的截止日期。 This way the total wait time is at most the given timeout-time.
这样,总等待时间最多为给定的超时时间。
What would be the simplest and most straightforward way to do this? 最简单,最直接的方法是什么?
Use the overload of thread::timed_join
that takes an absolute time (ie time point) instead of a duration. 使用
thread::timed_join
的重载,它需要一个绝对时间(即时间点)而不是持续时间。 Make that absolute time deadline be the current time plus whatever timeout duration you desire. 使绝对时间截止日期为当前时间加上您想要的任何超时持续时间。 This will ensure that none of
thread::timed_join
calls in the loop will wait past the absolute time deadline. 这将确保循环中没有
thread::timed_join
调用将等待超过绝对时间期限。
In the latest version of Boost.Thread (as of Boost 1.50), Boost.Date_Time is now deprecated in favor of Boost.Chrono . 在Boost.Thread的最新版本中(从Boost 1.50开始),现在不推荐使用Boost.Date_Time来支持Boost.Chrono 。 This is to closer match the API of std::thread in C++11.
这是为了更接近C ++ 11中std :: thread的API。
This example shows how to specify an absolute time deadline with either Boost.Chrono or Boost.DateTime: 此示例显示如何使用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);
}
This page in the documentation shows Boost.Date_Time example usages. 文档中的此页面显示了Boost.Date_Time示例用法。
This page in the documentation is a tutorial on Boost.Chrono. 文档中的这个页面是关于Boost.Chrono的教程。
int64_t mseconds = 60*1000; // 60 seconds
simply use 简单地用
threads[i]->timed_join(boost::posix_time::milliseconds(mseconds ))
you dont need to use absolute time 你不需要使用绝对时间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.