timer in a thread with pthread in C?
in threads, i need to periodically do some work in some different intervals, what 开发者_开发问答would be a good way to do this? With sleep(), then i need keep track of the interval to the next wakeup, which doesn't seem to be the best way.
thanks.
You can use clock_nanosleep
with the TIMER_ABSTIME
flag to work with absolute times instead of relative times for your sleep. That will avoid error accumulation problems and race conditions where your program gets interrupted and another process scheduled after getting the current time but before calling sleep.
Alternatively you could use POSIX timers (timer_create
) with a signal handler, where the signal you choose is blocked in all threads but yours, or with timer delivery in a new thread that signals a condition variable or semaphore your thread is waiting on.
Depends on how much accuracy you need:
- you can use clock_gettime Which is very accurate (~10MHz). (Go with the realtime or monotonic clock)
- If resolution and overhead is not a problem, but instead you would like to get the real-world time you can also you gettimeofday
精彩评论