如何在C ++中实现函数超时 [英] How to implement timeout for function in c++

查看:492
本文介绍了如何在C ++中实现函数超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有函数f;
我想在开始f之后引发异常1s。
我无法修改f()。

I have got function f; I want to throw exception 1s after start f. I can't modify f(). It it possible to do it in c++?

try {
   f();
}
catch (TimeoutException& e) {
//timeout
}


推荐答案

您可以创建一个单独的线程来运行调用本身,并在主线程中等待条件变量返回,该变量将由执行该调用的线程发出信号返回后返回 f 。诀窍是等待条件变量以1s的超时时间,这样,如果调用花费的时间超过超时时间,您仍将醒来,知道它,并能够引发异常-全部在主线程中。这是代码(实时演示此处):

You can create a separate thread to run the call itself, and wait on a condition variable back in your main thread which will be signalled by the thread doing the call to f once it returns. The trick is to wait on the condition variable with your 1s timeout, so that if the call takes longer than the timeout you will still wake up, know about it, and be able to throw the exception - all in the main thread. Here is the code (live demo 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 ++中实现函数超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆