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:
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.
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.