背景
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++