Timer in thread with pthread in C?

in threads, I need to do some work periodically at several different intervals, what would be a good way to do this? With sleep (), I need to monitor the interval until the next wake up, which does not seem to be the best way.

thanks.

+4
source share
2 answers

You can use clock_nanosleep with the TIMER_ABSTIME flag to work with absolute times instead of relative times for your sleep. This will avoid problems with the accumulation of errors and race conditions, when your program is interrupted, and another process is scheduled after receiving the current time, but before the call of sleep.

Alternatively, you can use POSIX timers ( timer_create ) with a signal handler where the signal of your choice is blocked in all threads except yours, or delivered by timer in a new thread that signals a state variable or semaphore, your thread is waiting.

+8
source

Depending on how much accuracy you need:

  • you can use clock_gettime. This is very accurate (~ 10 MHz). (Go in real time or in monotonous hours)
  • If permission and overhead are not a problem, but instead you would like to get real time, you can also gettimeofday
+1
source

Source: https://habr.com/ru/post/1346297/


All Articles