Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly add to timespec variables

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading