Implementing timer using select
I am planning to write a small timer library in C using timerfd_create
.
The basic user of this library will have two threads
- application thread
- Timer thread
There will be a queue between these two threads so that whenever the application wants to start a timer, it will push a message into the queue which the timer thread will then read and create an FD for it and put it in select
.
The problem with the above approach is that the timer thread being a single thread would be blocked in the select
system call and would not know if a message has been posted in his receive queue to start a timer.
One way around this is to let the select timeout every "tick" and then check for messages in the queue. Is their a better way to do this?
I was also thinking of raising an Interrupt every time the app开发者_如何学编程lication puts a message in the select
queue to interrupt the select
. Does that work well with Multi-threaded applications?
Platform : Unix
If you insist on having multiple threads post timers to a dedicated timer thread sitting in select(2)
, then why not use eventfd(2)
or just an old-good self-pipe trick to signal that new timers are available. Include the event file descriptor to the pollable set, wait on all of them.
Which platform(s) are you wanting to target? Under Windows, for instance, there are much better ways to handle this without using select(), such as PostThreadMessage() and WaitMessage().
If you are using timerfd's then there is no need for a dedicated timer thread, just write the application around an event loop using select
, poll
, or epoll
, etc.
精彩评论