c++ - 如何在c++中实现函数超时

标签 c++ c++11 time timeout

我有函数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/

相关文章:

c++ - C++ 中用户定义数组的问题

c++ - 重载运算符 new

c++ - 尝试调用构造函数,收到 "no matching function call"编译错误

c++ - ‘operator>>’ 中 ‘std::cin >>' 的模糊重载

c++ - 多态性和 shared_ptr 通过引用传递

java - 国家时区、夏令时是否有效

python - 为什么 python timeit 结果与 shell 的时间命令相矛盾?

c++ - 以编程方式确定我正在运行的发行版

c++ - 将 if-else 转换为 for 循环

android - ACTION_TIME_CHANGED 或 ACTION_DATE_CHANGED,不能使它们工作