我有函数f; 我想在开始 f 后抛出异常 1s。 我无法修改 f()。可以用 C++ 实现吗?
try {
f();
}
catch (TimeoutException& e) {
//timeout
}
最佳答案
您可以创建一个单独的线程来运行调用本身,并在主线程中等待条件变量返回,一旦返回,调用 f
的线程将发出信号。诀窍是用 1s 超时等待条件变量,这样如果调用花费的时间比超时时间长,您仍然会醒来,了解它,并能够抛出异常 - 所有这些都在主线程中进行。这是代码(现场演示 here ):
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std::chrono_literals;
int f()
{
std::this_thread::sleep_for(10s); //change value here to less than 1 second to see Success
return 1;
}
int f_wrapper()
{
std::mutex m;
std::condition_variable cv;
int retValue;
std::thread t([&cv, &retValue]()
{
retValue = f();
cv.notify_one();
});
t.detach();
{
std::unique_lock<std::mutex> l(m);
if(cv.wait_for(l, 1s) == std::cv_status::timeout)
throw std::runtime_error("Timeout");
}
return retValue;
}
int main()
{
bool timedout = false;
try {
f_wrapper();
}
catch(std::runtime_error& e) {
std::cout << e.what() << std::endl;
timedout = true;
}
if(!timedout)
std::cout << "Success" << std::endl;
return 0;
}
关于c++ - 如何在c++中实现函数超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550730/