特定时间后打破功能.(C )

Break the function after certain time. (C++)

本文关键字:功能 定时间      更新时间:2023-10-16

我的问题与以下问题完全共鸣。

在特定时间后打破功能

但是,上面的问题围绕Python实施。我正在尝试在C 中实现同一件事。这是代码:

#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdexcept>
void handle_alarm( int sig ) {
    printf("%d",sig); 
    throw std::invalid_argument("none");
}
int main() {
    for (int i=0; i<10; i++){
        signal( SIGALRM, handle_alarm ); 
        printf("Doing normal work %d n",i);
        alarm(120);
        try {
            for (;;){}    // It will be replaced by a function which can take very long time to evaluate.
        }
        catch(std::invalid_argument& e ) {
        continue; 
        } 
    }   
}

问题语句

:循环的每次迭代,XYZ的函数XYZ可能需要很长时间的评估(用上述代码中的无限循环代替)。我的目标是终止该功能的执行,如果需要超过2分钟,并继续进行下一个迭代。

但是,这给了我错误 terminate called after throwing an instance of 'std::invalid_argument'。我还尝试使用自定义异常类,但是错误仍然存在。

我无法弄清楚此特定实现的问题,或者是否存在另一种更好的方法?任何帮助将不胜感激。

解决问题的一种方法是将std::asyncasync启动策略一起使用。

然后,您可以使用返回的std::futurewait_for仅等待结果。

如果您在时间范围内没有得到结果,请保存未来(直到有结果之前就不会破坏它!),但只忽略它及其可能的结果。

这不会真正"破坏"功能,直到完成。但这是一种继续您的程序的方法。


另一个可能的解决方案是使用线程,并在其中不断检查超时,或为某些(原子)标志知道是否应该继续。