c++ - 为 c/c++ 函数调用设置超时
问题描述
假设我的主函数调用了一个外部函数veryslow()
int main(){... veryslow();..}
现在我想在 main 中调用very_slow 的部分,这样如果超过时间限制,veryslow 就会终止。像这样的东西
int main(){... call_with_timeout(veryslow, 0.1);...}
实现这一目标的简单方法是什么?我的操作系统是 Ubuntu 16.04。
解决方案
你可以在一个新线程中调用这个函数,并设置一个超时来终止线程,它会结束这个函数调用。
一个 POSIX 示例是:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
pthread_t tid;
// Your very slow function, it will finish running after 5 seconds, and print Exit message.
// But if we terminate the thread in 3 seconds, Exit message will not print.
void * veryslow(void *arg)
{
fprintf(stdout, "Enter veryslow...\n");
sleep(5);
fprintf(stdout, "Exit veryslow...\n");
return nullptr;
}
void alarm_handler(int a)
{
fprintf(stdout, "Enter alarm_handler...\n");
pthread_cancel(tid); // terminate thread
}
int main()
{
pthread_create(&tid, nullptr, veryslow, nullptr);
signal(SIGALRM, alarm_handler);
alarm(3); // Run alarm_handler after 3 seconds, and terminate thread in it
pthread_join(tid, nullptr); // Wait for thread finish
return 0;
}
推荐阅读
- reactjs - ReactPress 手动模式:Wordpress 需要访问 npm
- python - How to find and compare text with the style property using Selenium/Python?
- angular - Integrate Angular Material theme into existing ngx-admin project
- android - 如何在 Room 中插入一组可为空的实体?
- css - 由于 MIME 类型(“text/html”)不匹配而被阻止的 css 样式表
- c - 如何写()\ n的十六进制表示?
- android - 未处理的异常:“int”类型不是“String”类型的子类型
- mysql - 从运行 nodejs 应用程序的 docker 容器连接到在主机上运行的 mysql 数据库
- javascript - 如何在 hbs 页面中显示存储在远程服务器上的图像?这甚至可能吗?
- ruby-on-rails - 拆分轨道活动记录模型