加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C中设置一个函数的超时?

发布时间:2020-12-16 03:12:57 所属栏目:百科 来源:网络整理
导读:我有一个要求,我必须给xx ms执行一个功能. xx ms后,我必须中止这个功能.请帮助我如何在C. 解决方法 我认为最好的方法是涉及pthreads.开始可能需要在自己的线程中取消的计算,在主线程中使用pthread_cond_timedwait: #include time.h#include pthread.h#inclu
我有一个要求,我必须给xx ms执行一个功能. xx ms后,我必须中止这个功能.请帮助我如何在C.

解决方法

我认为最好的方法是涉及pthreads.开始可能需要在自己的线程中取消的计算,在主线程中使用pthread_cond_timedwait:
#include <time.h>
#include <pthread.h>
#include <stdio.h>
/* for ETIMEDOUT */
#include <errno.h>
#include <string.h>

pthread_mutex_t calculating = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t done = PTHREAD_COND_INITIALIZER;

void *expensive_call(void *data)
{
        int oldtype;

        /* allow the thread to be killed at any time */
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);

        /* ... calculations and expensive io here,for example:
         * infinitely loop
         */
        for (;;) {}

        /* wake up the caller if we've completed in time */
        pthread_cond_signal(&done);
        return NULL;
}

/* note: this is not thread safe as it uses a global condition/mutex */
int do_or_timeout(struct timespec *max_wait)
{
        struct timespec abs_time;
        pthread_t tid;
        int err;

        pthread_mutex_lock(&calculating);

        /* pthread cond_timedwait expects an absolute time to wait until */
        clock_gettime(CLOCK_REALTIME,&abs_time);
        abs_time.tv_sec += max_wait->tv_sec;
        abs_time.tv_nsec += max_wait->tv_nsec;

        pthread_create(&tid,NULL,expensive_call,NULL);

        /* pthread_cond_timedwait can return spuriously: this should
         * be in a loop for production code
         */
        err = pthread_cond_timedwait(&done,&calculating,&abs_time);

        if (err == ETIMEDOUT)
                fprintf(stderr,"%s: calculation timed outn",__func__);

        if (!err)
                pthread_mutex_unlock(&calculating);

        return err;
}

int main()
{
        struct timespec max_wait;

        memset(&max_wait,sizeof(max_wait));

        /* wait at most 2 seconds */
        max_wait.tv_sec = 2;
        do_or_timeout(&max_wait);

        return 0;
}

你可以在linux上编译并运行它:

$gcc test.c -pthread -lrt && ./a.out
do_or_timeout: calculation timed out

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读