Loops/timers in C Loops/timers in C linux linux

Loops/timers in C


Simplest method available:

#include <pthread.h>void *do_smth_periodically(void *data){  int interval = *(int *)data;  for (;;) {    do_smth();    usleep(interval);  }}int main(){  pthread_t thread;  int interval = 5000;  pthread_create(&thread, NULL, do_smth_periodically, &interval)  ...}


On POSIX systems you can create (and catch) an alarm. Alarm is simple but set in seconds. If you need finer resolution than seconds then use setitimer.

struct itimerval tv;tv.it_interval.tv_sec = 0;tv.it_interval.tv_usec = 100000;  // when timer expires, reset to 100mstv.it_value.tv_sec = 0;tv.it_value.tv_usec = 100000;   // 100 ms == 100000 ussetitimer(ITIMER_REAL, &tv, NULL);

And catch the timer on a regular interval by setting sigaction.


One doesn't "create a timer in C". There is nothing about timing or scheduling in the C standard, so how that is accomplished is left up to the Operating System.

This is probably a reasonable question for a C noob, as many languages do support things like this. Ada does, and I believe the next version of C++ will probably do so (Boost has support for it now). I'm pretty sure Java can do it too.

On linux, probably the best way would be to use pthreads. In particular, you need to call pthread_create() and pass it the address of your routine, which presumably contains a loop with a sleep() (or usleep()) call at the bottom.

Note that if you want to do something that approximates real-time scheduling, just doing a dumb usleep() isn't good enough because it won't account for the execution time of the loop itself. For those applications you will need to set up a periodic timer and wait on that.