Alex Rivera | Logout

Best way to do a timer in Unix

Asked 2011-08-25T14:37:48.610
15

I always notice people have different reactions to different ways of creating a timer in Unix.

I know a few different ways that I could make an event execute every X seconds within Unix:

  • you can do a polling thread - pthread_t with sleeps;
  • you can do a select() with a timeout;
  • and I guess you can use the OS in a few other ways.

Can someone provide some sample code with the "best" or most efficient way to do a timer and a description of why it is the best? I'd like to use the most efficient mechanism for this but I'm not sure which one it is!

For our purposes, just pretend you're printing "Hello, World!" once every 10 seconds.

Note: I don't have TR1, Boost, etc. on this system, so please keep it to straight-up C/C++ and Unix system calls.

Edit
Report

2 Answers

6

It depends on what you are wanting to do. A simple sleep will suffice for your trivial example of waiting 10 seconds between "Hello"s since you might as well suspend your current thread until your time is up.

Things get more complicated if your thread is actually doing something while you are waiting. If you are responding to incoming connections, you will already be using select in such a case a timeout to your select statement makes the most sense for your housekeeping.

If you are processing stuff in a tight loop, you might regularly poll a start time to see if your 10 seconds are up.

alarm with an appropriate signal handler will work as well, but there are severe limits to what you can do in a signal handler. Most of the time, it involved setting a flag that will need to be polled every so often.

In a nutshell, it comes down to how your thread is processing events.

answered 2011-08-25T14:52:41.073
1

Here is my implementation of a timer. It is a threaded timer, and needs some work, with wrapping up mutexes and POSIX Threads in their own classes (lack of RAII in that respect). It is also not cross-platform since it uses the gettimeofday() method.

The code uses a timer that calls on a CallBack object. The entire source can be seen at

http://matthewh.me/playground/browser/branches/C%2B%2B/c%2B%2B_callbacks

answered 2012-07-26T03:27:22.127

Your Answer