linux high resolution timer in user space
linux, linux-kernel, posix
Solution
The POSIX timers (created with `timer_create()`) are already high-resolution. Your problem is in the delivery method - if you want very precise timing then `SIGEV_THREAD` is not a good idea.
You could instead use `SIGEV_SIGNAL` so that timer expiry is notified via a signal, then use `sigwaitinfo()` to wait for it to expire. Alternately, you could use a timerfd instead of a POSIX timer (created with `timerfd_create()`).
Additionally, if you want your thread to preempt other running threads when the timer expires, you'll need to give it a real-time scheduling policy (`SCHED_FIFO` or `SCHED_RR`) with `sched_setscheduler()`.
You will also want to ensure that your kernel is compiled with the `CONFIG_PREEMPT` option, which allows most kernel code to be preemptable. There will still be some level of jitter, caused by non-preemptible kernel work like hardware interrupts and softirqs. To reduce this further, you can try using the `CONFIG_PREEMPT_RT` kernel patchset.
Problem
I need a thread in my process to wakeup every 5ms(precise) and do some work. I have used posix timers, they seems to be accurate 90% and accuracy further decreases when cpu is somewhat loaded. I believe that is because posix timer have to fork new thread on every expiry. Is there some other reliable way to implement high resolution timer in linux and will increasing priority of thread help? I am on CentOS 5.6.