wei
wei

Reputation: 6889

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.

Upvotes: 4

Views: 8911

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

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

Ronny Brendel
Ronny Brendel

Reputation: 4845

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

Upvotes: 1

Related Questions