定期调用函数而不使用c中的thread和sleep()方法
我想调用一个函数,让我们说每10或20秒。 当我搜索时,我到处想出了线程和sleep()
方法。
我还检查了C中的时间和时钟类,但我找不到任何有用的问题。
定期调用函数的最简单方法是什么?
在我看来,使用libevent
是更清洁的解决方案,因为在此期间,你可以做其他操作(甚至其他定时function)
看看这个简单且自我解释的例子,每3秒打印一次Hello:
#include #include #include void say_hello(int fd, short event, void *arg) { printf("Hello\n"); } int main(int argc, const char* argv[]) { struct event ev; struct timeval tv; tv.tv_sec = 3; tv.tv_usec = 0; event_init(); evtimer_set(&ev, say_hello, NULL); evtimer_add(&ev, &tv); event_dispatch(); return 0; }
大多数操作系统都有办法“设置警报”或“设置计时器”,这将在未来的某个特定时间调用您的function。 在linux中,你使用alarm
,在Windows中你使用SetTimer
。
这些函数限制你可以在被调用的函数中做什么,并且你几乎肯定会最终得到最终有多个线程的东西 – 尽管线程可能没有调用sleep
,而是一些wait_for_event
或类似的函数代替。
编辑:但是,使用包含以下内容的线程的线程:
while(1) { sleep(required_time); function(); }
问题以一种非常直接的方式解决,以解决问题,并使其易于处理。
一个天真的解决方案是这样的:
/* Infinite loop */ time_t start_time = time(NULL); for (;;) { time_t now = time(NULL); time_t diff = now - start_time; if ((diff % 10) == 0) { /* Ten seconds has passed */ } if ((diff % 20) == 0) { /* Twenty seconds has passed */ } }
您可能需要一个标志来告诉函数是否已被调用,或者它将在单秒内被调用多次(diff % 10) == 0
为真。
试试这个:
while(true) { if(System.getNanotime % 20 == 0) { myFunction(); } }
这是Java-Syntax,我没有编程c超过5年,但也许它可以帮助你:)
简单:
#include #include int main(int argc, const char** argv) { while(1) { usleep(20000) ; printf("tick!\n") ; } }
请注意,usleep()当然会阻止:)