在 C 中每 x 秒执行一个方法 [英] Execute a method every x seconds in C
问题描述
是否有一个工作定时器的例子,它使用 C 每隔 x 秒执行一些函数.
Is there an example of a working timer that executes some function every x amount seconds using C.
如果有示例工作代码,我会很感激.
I'd appreciate an example working code.
推荐答案
您可以创建一个新线程:
You could spawn a new thread:
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)
:
Or, you could set an alarm with alarm(2)
or 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
当然,这两种方法都存在问题,即您定期调用的函数需要是线程安全的.
Of course, both of these methods have the problem that the function you're calling periodically needs to be thread-safe.
信号方法特别危险,因为它也必须是异步安全的,这很难做到——即使像printf
这样简单的东西也是不安全的,因为printf
可能会分配内存,如果 SIGALRM
中断了对 malloc
的调用,你就会遇到麻烦,因为 malloc
是不可重入的.所以我不推荐使用信号方法,除非你所做的只是在信号处理程序中设置一个标志,该标志稍后会被其他一些函数检查,这会让你回到与线程版本相同的位置.
The signal method is particularly dangerous because it must also be async-safe, which is very hard to do -- even something as simple as printf
is unsafe because printf
might allocate memory, and if the SIGALRM
interrupted a call to malloc
, you're in trouble because malloc
is not reentrant. So I wouldn't recommend the signal method, unless all you do is set a flag in the signal handler which later gets checked by some other function, which puts you back in the same place as the threaded version.
这篇关于在 C 中每 x 秒执行一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!