Reputation: 6889
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.
Upvotes: 4
Views: 8911
Reputation: 215183
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.
Upvotes: 8
Reputation: 4845
Depends on how much accuracy you need:
Upvotes: 1