设置 c/c++ 函数调用的超时

Setting timeout for c/c++ function call

本文关键字:超时 函数调用 c++ 设置      更新时间:2023-10-16

>假设我的主函数调用外部函数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

我会将指向接口的指针传递到函数中并请求一个返回。 有了这个,我将启用双向通信来执行所有必要的任务 - 包括超时和超时通知。