gpt4 book ai didi

c - 如何在 C 中为函数设置超时?

转载 作者:太空狗 更新时间:2023-10-29 16:38:18 25 4
gpt4 key购买 nike

我有一个要求,我必须给 xx 毫秒才能执行一个功能。在 xx 毫秒后,我必须中止该功能。请帮助我如何在 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 out\n", __func__);

if (!err)
pthread_mutex_unlock(&calculating);

return err;
}

int main()
{
struct timespec max_wait;

memset(&max_wait, 0, 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

关于c - 如何在 C 中为函数设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7738546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com