select() is a great system call. You can pack any number of file descriptors, socket descriptors, pipes, etc. and get notified in a synchronous fashion when input becomes available.
Is there a way to create an interval/oneshot timer and use it with select()? That would save me from having multiple threads for IO and timing.
timerfd_create does exactly this. It's a fairly recent addition to the linux kernel and might not be available on all distros yet though.
Use the timeout parameter - keep your timer events in a priority queue, check the top item and set the timeout accordingly - if the timeout is reached, then you can check that the event is ready to run, run the event and continue.
At least that's what I do.
Note that poll has a nicer interface (in some ways) and may be more efficient with lots of file descriptors.
MarkR has a nice portable solution, but here's another:
Use a POSIX timer (timer_create
) and you can transform the problem into "select
-able signals". This problem has a classic solution: writing to a pipe from the signal handler and select
ing on the read end of the pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With