设置 c/c++ 函数调用的超时
Setting timeout for c/c++ function call
>假设我的主函数调用外部函数veryslow((
int main(){... veryslow();..}
现在我想在main中调用very_slow的部分,以便在超出时间限制时非常慢终止。像这样的东西
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;
}
您可以使用超时future
。
std::future<int> future = std::async(std::launch::async, [](){
veryslow();
});
std::future_status status;
status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::timeout) {
// verySlow() is not complete.
} else if (status == std::future_status::ready) {
// verySlow() is complete.
// Get result from future (if there's a need)
auto ret = future.get();
}
请注意,没有取消异步任务的内置方法。您必须在verySlow
本身中实现它。
请参阅此处了解更多信息:
http://en.cppreference.com/w/cpp/thread/future/wait_for
我会将指向接口的指针传递到函数中并请求一个返回。 有了这个,我将启用双向通信来执行所有必要的任务 - 包括超时和超时通知。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 设置 c/c++ 函数调用的超时
- Qt:QFuture/Qt并发超时函数调用