Home > Back-end >  How to properly add to timespec variables
How to properly add to timespec variables

Time:04-08

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);

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related