首页 > 解决方案 > 为 c/c++ 函数调用设置超时

问题描述

假设我的主函数调用了一个外部函数veryslow()

int main(){... veryslow();..}

现在我想在 main 中调用very_slow 的部分,这样如果超过时间限制,veryslow 就会终止。像这样的东西

int main(){... call_with_timeout(veryslow, 0.1);...}

实现这一目标的简单方法是什么?我的操作系统是 Ubuntu 16.04。

标签: c++timeout

解决方案


你可以在一个新线程中调用这个函数,并设置一个超时来终止线程,它会结束这个函数调用。

一个 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;
}

推荐阅读