1

I'm basically trying to set a timer to wait for a specified amount of seconds from the current time. I know that timespec's tv_sec only includes whole numbers. So I'm struggling what to do if I need to wait for 1.5 or 0.1 seconds.

Here's the bit of code I have for it:

struct timespec timeToWait;
        clock_gettime(CLOCK_REALTIME, &timeToWait);
        int rt;

        timeToWait.tv_sec += p1->intrval; //adding specified wait time
        pthread_mutex_lock(&lock);
        do{
                rt = pthread_cond_timedwait(&cond,&lock,&timeToWait);
        }while (rt == 0);
        pthread_mutex_unlock(&lock);

1 Answers1

0

A struct timespec has another field called tv_nsec which specifies the nanosecond portion.

So if you want to wait for 1.5 seconds, add 1 to timeToWait.tv_sec and add 500000000 to timeToWait.tv_nsec. If after doing that, timeToWait.tv_nsec is larger than 1000000000, then subtract 1000000000 from timeToWait.tv_nsec and add one more to timeToWait.tv_sec.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Ok. So if I don't know what the specified wait time is could I do something like: `timeToWait.tv_nsec += (p1->interval - (int)p1->interval)*100000000` and then check if its larger than a billion? – Dad2theMax Apr 08 '22 at 02:35
  • Just tried and it works. Thank you very much! – Dad2theMax Apr 08 '22 at 02:41
  • @Dad2theMax Recheck the zero count in `*100000000`. Your testing may have been insufficient. `(p1->interval - (int)p1->interval)` is a dodgy way to get the fraction. Research `trunc()`. – chux - Reinstate Monica Apr 08 '22 at 02:50