特定时间后打破功能.(C )
Break the function after certain time. (C++)
我的问题与以下问题完全共鸣。
在特定时间后打破功能
但是,上面的问题围绕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::async
与async
启动策略一起使用。
然后,您可以使用返回的std::future
的wait_for
仅等待结果。
如果您在时间范围内没有得到结果,请保存未来(直到有结果之前就不会破坏它!),但只忽略它及其可能的结果。
这不会真正"破坏"功能,直到完成。但这是一种继续您的程序的方法。
另一个可能的解决方案是使用线程,并在其中不断检查超时,或为某些(原子)标志知道是否应该继续。
相关文章:
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 控制台打印时间功能产生1
- 不同C++功能的编译时间
- 以小于一毫秒的精度计算时间的功能
- 如何实现声明功能-C 11,编译时间
- 使用提升功能与地图绑定提升
- 绑定和提升功能
- 如何在 python 交易模型中创建功能时间条件
- C++ Poco SQL 查询不返回具有'between'和'and'日期时间绑定的结果
- C++ 由于无法解决过载功能而导致绑定失败
- C 使用多个lambdas/绑定以引用相同的功能
- 实现功能对象绑定而无需使用C 11
- C++功能的时间限制
- 尝试将简单按钮绑定到SFGUI中的OnClick功能
- 功能执行时间很奇怪
- TIM6,基本时间生成功能不起作用
- 在Visual Studio Enterprise 2017(C )中测量功能执行时间
- 如何在QT中测量功能运行时间
- 示例功能处理时间装饰器在C 11中
- 模板变量的绑定时间