The title says it all. I have seen solutions in C++. For example, this one and some which (also C++) are rather old. I am open to using glib or any other opensource library. I care only for Linux implementation.
I came across glib's timer functions but they are all synchronous in nature and not close to what setTimeout() does.
I can think of one solution of having a separate thread which continually, in a loop, checks if a timer, such as the one provided by Glib, has expired and then fire the corresponding function. Of course, that would be ridiculously inefficient.
I also came across this one here which suggests the use of alarm(2). It can be used but granularity is in seconds only.
EDIT: Alas alarm() cancels any previously set alarm()
You mention that you need more than one timer in your process, so you might want the POSIX timer_*
family of functions (timer_create
, timer_settime
, etc). They have nanosecond granularity. You can specify a few different actions for when the timer expires: raise a signal, or call a function from a separate thread. You have to link with -lrt
to use these functions.
There is also timerfd_create
, which let you detect timer expiration by a file becoming readable, using poll
or select
or their relatives.