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

时间:2018-06-05 03:16:58

标签: c++ timeout

假设我的main函数调用外部函数veryslow()

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

现在我想在main中调用very_slow的部分,以便veryslow在时间限制之外终止。像这样的东西

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:0)

您可以在新线程中调用此函数,并设置超时以终止该线程,它将结束此函数调用。

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

答案 2 :(得分:0)

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