Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loops/timers in C

Tags:

c

linux

loops

timer

How does one create a timer in C?

I want a piece of code to continuously fetch data from a gps parsers output.

Are there good libraries for this or should it be self written?

like image 360
some_id Avatar asked Apr 04 '11 14:04

some_id


3 Answers

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)

  ...
}
like image 166
Marko Kevac Avatar answered Oct 12 '22 17:10

Marko Kevac


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 100ms
tv.it_value.tv_sec = 0;
tv.it_value.tv_usec = 100000;   // 100 ms == 100000 us
setitimer(ITIMER_REAL, &tv, NULL);

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

like image 33
Thomas M. DuBuisson Avatar answered Oct 12 '22 18:10

Thomas M. DuBuisson


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.

like image 4
T.E.D. Avatar answered Oct 12 '22 17:10

T.E.D.