Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timer in a thread with pthread in C?

Tags:

c

pthreads

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.

like image 519
wei Avatar asked Jan 20 '23 02:01

wei


2 Answers

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.

like image 168
R.. GitHub STOP HELPING ICE Avatar answered Feb 04 '23 14:02

R.. GitHub STOP HELPING ICE


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
like image 21
Ronny Brendel Avatar answered Feb 04 '23 14:02

Ronny Brendel