[英]Setting timeout for c/c++ function call
假设我的主函数调用了一个外部函数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;
}
您可以将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
内部实现该verySlow
。
看到这里更多:
我会向该函数传递一个指向接口的指针,并要求返回一个指针。 有了这个,我将启用双向通信来执行所有必要的任务-包括超时和超时通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.