是否有一个工作定时器的例子,它使用 C 每 x 秒执行一些功能。
我会很感激一个示例工作代码。
最佳答案
你可以产生一个新线程:
void *threadproc(void *arg)
{
while(!done)
{
sleep(delay_in_seconds);
call_function();
}
return 0;
}
...
pthread_t tid;
pthread_create(&tid, NULL, &threadproc, NULL);
或者,您可以使用 alarm(2)
设置闹钟或 setitimer(2)
:
void on_alarm(int signum)
{
call_function();
if(!done)
alarm(delay_in_seconds); // Reschedule alarm
}
...
// Setup on_alarm as a signal handler for the SIGALRM signal
struct sigaction act;
act.sa_handler = &on_alarm;
act.sa_mask = 0;
act.sa_flags = SA_RESTART; // Restart interrupted system calls
sigaction(SIGALRM, &act, NULL);
alarm(delay_in_seconds); // Setup initial alarm
当然,这两种方法都有一个问题,即您定期调用的函数需要是线程安全的。
signal 方法特别危险,因为它还必须是异步安全的,这很难做到——即使像 printf
这样简单的方法也是不安全的,因为 printf
可能会分配内存,如果 SIGALRM
中断了对 malloc
的调用,您就会遇到麻烦,因为 malloc
不可重入。所以我不推荐信号方法,除非你所做的只是在信号处理程序中设置一个标志,该标志稍后会被其他一些函数检查,这会让你回到与线程版本相同的位置。
关于c - 在 C 中每 x 秒执行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923885/