views:

117

answers:

3

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 application puts a message in the select queue to interrupt the select. Does that work well with Multi-threaded applications?

Platform : Unix

A: 

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().

Remy Lebeau - TeamB
its Unix. I will add that to the question
Aditya Sehgal
It's obviously Linux, since `timerfd_create(2)` is Linux-specific.
Nikolai N Fetissov
A: 

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.

Steve-o
the actual application has 3 threads all of which can issue timer requests at any time.
Aditya Sehgal
+1  A: 

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.

Nikolai N Fetissov
that sounds interesting. I'll take a look. Thanks
Aditya Sehgal