C++限制函数最大执行时间
背景#
C++调用某些硬件操作(如TPU推理)可能存在超时风险,需要限制函数的执行时间。
思考#
异步执行免不了开线程,如何限制join的最大时间是关键。设计如下函数:
bool Infer(uint timeout_ms)
根据输入的timeout_ms参数,按时完成返回true超时返回false。
实现#
使用std::mutex
配合std::condiction_variable
实现有限的join时间。
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condiction_variable cv;
void DoWork()
{
// do the stuff
std::lock_guard<std::mutex> lock(m);
cv.notify_all();
}
bool Infer(uint timeout_ms)
{
std::thread(DoWork).detach();
std::unique_lock<std::mutex> lock(m);
std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(timeout_ms));
if(std::cv_status::timeout == status)
{
return false;
}
return true;
}
若DoWork()
是类成员函数或需要入参,考虑使用lambda传入匿名functor
std::thread([&]{\
DoWork(input, output);
std::lock_guard<std::mutex> lock(m);
cv.notify_all();
}).deatch();
拓展#
对于已经超时的thread怎么处理?
In C++, once the thread is detached or uses the detach() function, then we cannot stop such threads, and still, if there is a need for stopping such threads, then only one way is to return the thread from the initial thread function by instantiating it in main() function, adding the Boolean value but before exiting ...
看来detached thread并无行之有效的结束方法,尝试强行调用std::terminate()
会引发terminate called without an active exception
已知sub thread必须执行完成且无法安全退出,故可转换思路在main thread里做限制,发现超时强制休息N帧后再调用避免等待队列加深。
参考#
std::condition_variable::wait_for - cppreference.com
Lambda expressions (since C++11) - cppreference.com
C++ thread detach | Working of thread detach() Function in C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2022-02-21 python如何实现unzip方法?
2020-02-21 python变量加逗号,的含义
2020-02-21 搭建GithubPages静态博客踩过的坑
2020-02-21 树莓派zero w入坑指南
2020-02-21 Windows ThinPC 7 部署后续设置与本地化
2020-02-21 虚拟磁盘VHD文件压缩方法