没有(标准)方法可以进入线程并杀死它,无论如何这通常是个坏主意。更简洁的选择是将开始时间和最大持续时间传递给函数,然后(可能随着计算的进行多次)检查当前时间减去开始时间是否太长。
我会做这样的事情:
#include <chrono>
template <typename Clock = std::chrono::steady_clock>
class timeout
{
public:
typedef Clock clock_type;
typedef typename clock_type::time_point time_point;
typedef typename clock_type::duration duration;
explicit timeout(duration maxDuration) :
mStartTime(clock_type::now()),
mMaxDuration(maxDuration)
{}
time_point start_time() const
{
return mStartTime;
}
duration max_duration() const
{
return mMaxDuration;
}
bool is_expired() const
{
const auto endTime = clock_type::now();
return (endTime - start_time()) > max_duration();
}
static timeout infinity()
{
return timeout(duration::max());
}
private:
time_point mStartTime;
duration mMaxDuration;
};
这个简单的实用程序跟踪开始时间和最大持续时间(并提供一种指定无穷大的方法),并允许用户查询简单的事实,最重要的是是否发生超时。
下面测试;你可以通过定义/取消定义FAKE_DELAY来添加假延迟:
#include <iostream>
#include <future>
#define FAKE_DELAY
void fake_delay()
{
#ifdef FAKE_DELAY
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
#endif
}
void short_running_function(timeout<> timelimit)
{
fake_delay();
if (timelimit.is_expired())
std::cout << "short running thread ran out of time" << std::endl;
else
std::cout << "short running function finished" << std::endl;
}
void long_running_function(timeout<> timelimit)
{
for (unsigned i = 0; i < 10; ++i) {
if (timelimit.is_expired())
{
std::cout << "long running thread ran out of time" << std::endl;
return;
}
std::cout << "long running thread doing work" << std::endl;
fake_delay();
}
std::cout << "long running function finished" << std::endl;
}
int main()
{
std::async(short_running_function,
timeout<>(std::chrono::milliseconds(500))).wait();
std::async(short_running_function,
timeout<>(std::chrono::milliseconds(5000))).wait();
std::async(long_running_function,
timeout<>(std::chrono::milliseconds(500))).wait();
std::async(long_running_function,
timeout<>(std::chrono::milliseconds(5000))).wait();
std::async(long_running_function,
timeout<>::infinity()).wait();
}
FAKE_DELAYoff 的一种可能输出:
短跑功能完成
短跑功能完成
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行功能已完成
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行功能已完成
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行功能完成
FAKE_DELAYon 的一种可能输出:
短跑线程超时
短跑功能完成
长时间运行的线程正在工作
长时间运行的线程超时
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程超时
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行的线程正在工作
长时间运行功能完成