Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select()-able timers

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.

like image 659
Andrew Klofas Avatar asked Feb 24 '10 17:02

Andrew Klofas


3 Answers

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.

like image 83
nos Avatar answered Oct 31 '22 13:10

nos


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.

like image 7
MarkR Avatar answered Oct 31 '22 14:10

MarkR


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 selecting on the read end of the pipe.

like image 2
R.. GitHub STOP HELPING ICE Avatar answered Oct 31 '22 14:10

R.. GitHub STOP HELPING ICE